import { ReactElement, useEffect, useState, useMemo } from 'react';
import { drawerWidth } from 'layouts/main-layout';
import { GenericCategory, VendorAPI, VendorCategory, VendorItem } from 'types';
import DashboardTemplate from 'components/DasboardTemplate';
import CategoryGridTemplate from 'components/CategoryGridTemplate';
import VendorCategoryCard from 'components/sections/dashboard/Home/Vendor/VendorCategoryCard';
import ItemListDetailTemplate from 'components/ItemListDetailTemplate';
import VendorListItem from 'components/sections/dashboard/Home/Vendor/VendorListItem';
import VendorDetail from 'components/sections/dashboard/Home/Vendor/VendorDetail';
import { axiosInstance } from '../../axiosApi';
import {
  Box,
  Container,
  FormControl,
  FormControlLabel,
  InputLabel,
  MenuItem,
  Paper,
  Select,
  Switch,
  Typography,
} from '@mui/material';

const base_url: string = `${import.meta.env.VITE_API_URL?.replace('/api/', '')}/media/vendor_pictures/`;

// Define the array of corrected and alphabetized categories with 'as const'
const CATEGORY_NAMES = [
  'Arborist',
  'Basement Waterproofing And Injection',
  'Carpenter',
  'Cleaning Company',
  'Decking',
  'Door Company',
  'Electrician',
  'Fencing',
  'General Contractor',
  'Handyman',
  'Home Inspector',
  'House Staging',
  'HVAC',
  'Irrigation And Sprinkler System',
  'Junk Removal',
  'Landscaping',
  'Masonry',
  'Mortgage Lendor',
  'Moving Company',
  'Painter',
  'Paving Company',
  'Pest Control',
  'Photographer',
  'Plumber',
  'Pressure Washing',
  'Roofer',
  'Storage Facility',
  'Window Company',
  'Window Washing',
] as const;

const defaultCategoryImages: { [key in VendorType]: string } = {
  Arborist: `${base_url}arborist.png`,
  'Basement Waterproofing And Injection': `${base_url}basement.png`,
  Carpenter: `${base_url}carpenter.png`,
  'Cleaning Company': `${base_url}cleaning.png`,
  Decking: `${base_url}deck.png`,
  'Door Company': `${base_url}door.png`,
  Electrician: `${base_url}electrician.png`,
  Fencing: `${base_url}fencing.png`,
  'General Contractor': `${base_url}general_contractor.png`,
  Handyman: `${base_url}handyman.png`,
  'Home Inspector': `${base_url}home_inspector.png`,
  'House Staging': `${base_url}home_staging.png`,
  HVAC: `${base_url}hvac.png`,
  'Irrigation And Sprinkler System': `${base_url}irrigation.png`,
  'Junk Removal': `${base_url}junk_removal.png`,
  Landscaping: `${base_url}landscape.png`,
  'Mortgage Lendor': `${base_url}landscape.png`,
  Masonry: `${base_url}masonry.png`,
  'Moving Company': `${base_url}junk_removal.png`,
  Painter: `${base_url}painting.png`,
  'Paving Company': `${base_url}paving.png`,
  'Pest Control': `${base_url}pest_control.png`,
  Photographer: `${base_url}photography.png`,
  Plumber: `${base_url}plumber.jpg`,
  'Pressure Washing': `${base_url}power_washing.png`,
  Roofer: `${base_url}roofer.png`,
  'Storage Facility': `${base_url}storage.png`,
  'Window Company': `${base_url}window_installation.png`,
  'Window Washing': `${base_url}window_company.jpg`,
};

const CATEGRORY_DESCRIPTIONS: { [key in VendorType]: string } = {
  Arborist:
    'Connect with certified tree specialists for professional tree pruning, health assessment, and safe removal services. Keep your trees beautiful and your property protected.',
  'Basement Waterproofing And Injection':
    'Protect your biggest investment by finding experts in basement leak repair, foundation sealing, and effective moisture control solutions. Say goodbye to damp and musty spaces.',
  Carpenter:
    'Hire skilled craftsmen for custom built-ins, framing, trim work, and detailed wood repair projects around your home. Bring your vision of custom woodworking to life.',
  'Cleaning Company': `Find reliable residential and commercial cleaning services to maintain a spotless and healthy environment. Whether it's a deep clean or regular maintenance, they handle the dirty work.`,
  Decking:
    'Design and build the perfect outdoor living space with professionals specializing in new deck construction, repairs, and staining. Get ready to enjoy your backyard retreat.',
  'Door Company': `Install beautiful and secure entry, patio, and interior doors that enhance your home's curb appeal and energy efficiency. Upgrade your home's look and security.`,
  Electrician:
    'Get trusted service for wiring upgrades, lighting installation, electrical repairs, and safety inspections from licensed professionals. Power your home safely and efficiently.',
  Fencing:
    'Secure your property and enhance privacy with experts in wood, vinyl, metal, and chain-link fence installation and repair. Define your boundaries with style.',
  'General Contractor':
    'Oversee your entire home remodel, new construction, or major renovation project with a single trusted project manager. They coordinate all trades to complete your vision seamlessly.',
  Handyman:
    'For those small repairs and maintenance tasks that pile up, find a versatile professional to handle various jobs quickly and efficiently. Check off your to-do list with ease.',
  'Home Inspector': `Get a detailed, unbiased report on the condition of a potential home purchase or sale from a certified inspector. Know exactly what you're buying or selling before you close.`,
  'House Staging': `Prepare your home to sell faster and for a higher price with professional staging services that highlight your home's best features. Make a stunning first impression on potential buyers.`,
  HVAC: 'Keep your home comfortable year-round with experts in heating, ventilation, and air conditioning system repair, maintenance, and new installation. Control your climate efficiently.',
  'Irrigation And Sprinkler System': `Install, repair, and maintain efficient sprinkler systems that keep your lawn and garden healthy without wasting water. Automate your yard's watering needs.`,
  'Junk Removal':
    'Clear out clutter, construction debris, or unwanted items with fast and responsible hauling and disposal services. Reclaim your space and let them handle the heavy lifting.',
  Landscaping:
    'Transform your yard with design, installation, and maintenance services for beautiful lawns, gardens, and outdoor features. Create the perfect curb appeal and living space outside.',
  Masonry:
    'Restore or construct durable, attractive structures using brick, stone, and concrete for patios, walls, fireplaces, and foundations. Find skilled artisans for lasting results.',
  'Mortgage Lendor':
    'Connect with financing professionals to guide you through the process of securing a new home loan or refinancing your current one. Find the best rates and terms for your financial needs.',
  'Moving Company':
    'Hire reliable and insured movers for local or long-distance relocation, packing, and secure transportation of your belongings. Enjoy a smooth, stress-free move to your new home.',
  Painter: `Refresh your home's interior and exterior with professional painting services, including prep work, color consultation, and a flawless finish. Give your home a vibrant new look.`,
  'Paving Company':
    'Install and repair durable asphalt and concrete surfaces for driveways, walkways, and patios. Find experts to enhance the accessibility and curb appeal of your property.',
  'Pest Control':
    'Protect your home from unwanted guests like insects, rodents, and wildlife with effective, preventative, and removal treatments. Keep your home safe and pest-free.',
  Photographer:
    'Capture stunning, high-quality images of your property for real estate listings, rentals, or design portfolios. Professional photos make a significant difference in marketing your home.',
  Plumber:
    'For leaks, clogs, fixture installation, and water heater repair, connect with licensed plumbing professionals for reliable service. Ensure your water systems are running smoothly.',
  'Pressure Washing': `Revitalize your home's exterior, driveway, deck, and siding by removing dirt, grime, mold, and mildew. Bring back the original sparkle and brightness to your property.`,
  Roofer:
    'Find expert contractors for new roof installation, leak repair, and routine inspections to protect your home from the elements. Secure your home with a reliable, durable roof.',
  'Storage Facility':
    'Locate secure, convenient, and affordable short-term or long-term storage solutions for your personal or business belongings. Declutter your space without throwing things away.',
  'Window Company':
    'Upgrade your home with energy-efficient window replacement and installation to improve comfort and lower utility bills. Find the perfect styles to enhance natural light and aesthetics.',
  'Window Washing':
    'Schedule professional interior and exterior window cleaning to achieve streak-free, crystal-clear views. Let the natural light flood your home and boost your curb appeal.',
} as const;

export type VendorType = (typeof CATEGORY_NAMES)[number];
const Vendors = (): ReactElement => {
  const [allVendors, setAllVendors] = useState<VendorItem[]>([]);
  const [vendorCategories, setVendorCategories] = useState<VendorCategory[]>([]);
  const [hideEmptyCategories, setHideEmptyCategories] = useState<boolean>(true); // Default to true
  const [searchRadius, setSearchRadius] = useState<number>(10);

  // Simulate fetching data
  let fetchedVendors: VendorItem[] = [];
  useEffect(() => {
    const fetchData = async () => {
      const response = await axiosInstance.get<VendorAPI[]>('/vendors/');
      if (response.data.length > 0) {
        fetchedVendors = response.data.map((item) => {
          return {
            id: item.user.id,
            name: item.business_name,
            categoryId: item.business_type,
            phone: item.phone_number,
            email: item.user.email,
            address: item.address,
            contactPerson: item.user.first_name + ' ' + item.user.last_name,
            serviceAreas: item.service_areas,
            vendorImageUrl: 'https://via.placeholder.com/60?text=SE',
            rating: 4.5,
            servicesOffered: ['Residential wiring', 'Commercial electrical', 'Panel upgrades'],
            latitude: item.latitude,
            longitude: item.longitude,
          };
        });
        setAllVendors(fetchedVendors);
      }

      // Process categories based on fetched vendors
      const categoryMap = new Map<
        string,
        {
          name: string;
          description: string;
          imageUrl: string;
          numVendors: number;
          totalRating: number;
        }
      >();

      CATEGORY_NAMES.forEach((categoryName) => {
        const categoryId = categoryName.toLowerCase().replace(/\s+/g, '-');
        categoryMap.set(categoryId, {
          name: categoryName,
          description: CATEGRORY_DESCRIPTIONS[categoryName],
          imageUrl:
            defaultCategoryImages[categoryName] ||
            'https://via.placeholder.com/150/CCCCCC/000000?text=Category',
          numVendors: 0,
          totalRating: 0,
        });
      });

      fetchedVendors.forEach((vendor) => {
        const categoryId = vendor.categoryId;
        if (categoryMap.has(categoryId)) {
          const categoryData = categoryMap.get(categoryId)!;
          categoryData.numVendors += 1;
          categoryData.totalRating += vendor.rating;
        }
      });

      const processedCategories: VendorCategory[] = Array.from(categoryMap.entries()).map(
        ([id, data]) => ({
          id,
          name: data.name,
          description: data.description,
          imageUrl: data.imageUrl,
          numVendors: data.numVendors,
          categoryRating: data.numVendors > 0 ? data.totalRating / data.numVendors : undefined,
        }),
      );
      setVendorCategories(processedCategories);
    };

    fetchData();
  }, []);

  const filteredCategories = useMemo(() => {
    // 1. Hide empty categories if the toggle is set to true
    let categoriesToRender = vendorCategories;
    console.log(vendorCategories);
    if (hideEmptyCategories) {
      categoriesToRender = vendorCategories.filter((cat) => cat.numVendors > 0);
    }

    // 2. Geographic filtering based on searchRadius would go here.
    // This would typically involve user location and an API call/client-side distance calculation
    // filteredCategories = categoriesToRender.filter(category =>
    //   category.vendors.some(vendor => isWithinRadius(vendor.location, userLocation, searchRadius))
    // );

    return categoriesToRender;
  }, [vendorCategories, hideEmptyCategories, searchRadius]);

  return (
    <Container maxWidth="lg" sx={{ mt: 4 }}>
      {/* VENDOR FILTERS HEADER AND CONTROLS */}
      <Paper
        sx={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          mb: 2,
          flexWrap: 'wrap',
        }}
      >
        <Typography variant="h6" component="h2" sx={{ fontWeight: 'bold' }}>
          Vendor Filters
        </Typography>
        <Box
          sx={{
            display: 'flex',
            gap: 2,
            alignItems: 'center',
            mt: { xs: 1, sm: 0 },
          }}
        >
          {/* TOGGLE: Hide Categories with No Vendors */}
          <FormControlLabel
            control={
              <Switch
                checked={hideEmptyCategories}
                onChange={(e) => setHideEmptyCategories(e.target.checked)}
                name="hideEmpty"
                color="primary"
              />
            }
            label="Hide Empty Categories"
          />

          {/* DROPDOWN: Search Radius */}
          {/*<FormControl variant="outlined" sx={{ minWidth: 120 }} size="small">
            <InputLabel id="search-radius-label">Search Radius</InputLabel>
            <Select
              labelId="search-radius-label"
              id="search-radius-select"
              value={searchRadius}
              onChange={(e) => setSearchRadius(e.target.value as number)}
              label="Search Radius"
            >
              <MenuItem value={10}>10 miles</MenuItem>
              <MenuItem value={25}>25 miles</MenuItem>
              <MenuItem value={50}>50 miles</MenuItem>
            </Select>
          </FormControl>*/}
        </Box>
      </Paper>
      <DashboardTemplate<VendorCategory, VendorItem>
        pageTitle="Service Vendors"
        data={{ categories: filteredCategories, items: allVendors }}
        renderCategoryGrid={(categories, onSelectCategory) => (
          <CategoryGridTemplate
            categories={categories}
            onSelectCategory={(id) => onSelectCategory(id)}
            renderCategoryCard={(category, onSelect) => (
              <VendorCategoryCard
                category={category as VendorCategory}
                onSelectCategory={onSelect}
              />
            )}
          />
        )}
        renderItemListDetail={(selectedCategory, itemsInSelectedCategory, onBack) => (
          <ItemListDetailTemplate
            category={selectedCategory}
            items={itemsInSelectedCategory}
            onBack={onBack}
            renderListItem={(item, isSelected, onSelect) => (
              <VendorListItem
                vendor={item as VendorItem}
                isSelected={isSelected}
                onSelect={() => onSelect(item.id)}
              />
            )}
            renderItemDetail={(item) => (
              <VendorDetail vendor={item as VendorItem} showMessageBtn={true} />
            )}
          />
        )}
      />
    </Container>
  );
};

export default Vendors;
