
'use client';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import Link from 'next/link';
import { ChevronLeft, Trash2 } from 'lucide-react';
import { useRouter, useParams } from 'next/navigation';
import { servicesByCategory } from '@/lib/data';
import { useState, useEffect } from 'react';
import { Checkbox } from '@/components/ui/checkbox';
import type { Business, Category, Country, City } from '@/lib/types';
import { notFound } from 'next/navigation';
import Image from 'next/image';
import { useFirestore, useDoc, useCollection, useMemoFirebase } from '@/firebase';
import { doc, collection, updateDoc } from 'firebase/firestore';
import { updateDocumentNonBlocking } from '@/firebase/non-blocking-updates';
import { Switch } from '@/components/ui/switch';

const socialMediaPlatforms = [
    { id: 'facebook', name: 'Facebook' },
    { id: 'instagram', name: 'Instagram' },
    { id: 'twitter', name: 'Twitter' },
    { id: 'linkedin', name: 'LinkedIn' },
    { id: 'youtube', name: 'YouTube' },
    { id: 'tiktok', name: 'TikTok' },
];

const daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

type OpeningHoursState = {
  [key: string]: { open: string; close: string };
};

const generateTimeSlots = () => {
    const slots = [];
    for (let h = 0; h < 24; h++) {
        for (let m of ['00', '30']) {
            const hour = h.toString().padStart(2, '0');
            const time = `${hour}:${m}`;
            const ampm = h < 12 ? 'AM' : 'PM';
            const displayHour = h % 12 === 0 ? 12 : h % 12;
            slots.push({ value: time, label: `${displayHour}:${m} ${ampm}` });
        }
    }
    return slots;
};

const timeSlots = generateTimeSlots();


export default function EditBusinessPage() {
  const { toast } = useToast();
  const router = useRouter();
  const params = useParams();
  const businessId = params.id as string;
  const firestore = useFirestore();

  const businessDocRef = useMemoFirebase(() => firestore ? doc(firestore, 'businesses', businessId) : null, [firestore, businessId]);
  const { data: business, isLoading: isBusinessLoading } = useDoc<Business>(businessDocRef);

  const categoriesQuery = useMemoFirebase(() => firestore ? collection(firestore, 'categories') : null, [firestore]);
  const { data: categories } = useCollection<Category>(categoriesQuery);
  
  const countriesQuery = useMemoFirebase(() => firestore ? collection(firestore, 'countries') : null, [firestore]);
  const { data: allCountries } = useCollection<Country>(countriesQuery);
  
  const citiesQuery = useMemoFirebase(() => firestore ? collection(firestore, 'cities') : null, [firestore]);
  const { data: allCities } = useCollection<City>(citiesQuery);


  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [availableServices, setAvailableServices] = useState<string[]>([]);
  const [selectedCountryId, setSelectedCountryId] = useState<string>('');
  const [availableCities, setAvailableCities] = useState<City[]>([]);
  const [socialLinks, setSocialLinks] = useState<{ platform: string, link: string, id: number }[]>([]);
  const [nextSocialId, setNextSocialId] = useState(1);
  const [selectedSocialPlatform, setSelectedSocialPlatform] = useState(socialMediaPlatforms[0].id);
  const [openingHours, setOpeningHours] = useState<OpeningHoursState | null>(null);
  const [selectedServices, setSelectedServices] = useState<string[]>([]);
  const [isFeatured, setIsFeatured] = useState(false);

  useEffect(() => {
    if (business && categories && allCountries && allCities) {
        // Set Category
        const category = categories.find(c => c.name === business.category);
        if (category) {
          handleCategoryChange(category.id, business.services);
        }

        // Set Location
        const country = allCountries.find(c => c.name === business.country);
        if (country) {
            handleCountryChange(country.id);
        }
        
        // Set Featured
        setIsFeatured(business.isFeatured || false);

        // Set Social Media Links (assuming they're in the website for now)
        // A better data model would store these separately
        
        // Set Opening Hours
        const hoursState: OpeningHoursState = {};
        daysOfWeek.forEach(day => {
            const dayInfo = business.openingHours.find(oh => oh.day === day);
            if (dayInfo && dayInfo.hours.toLowerCase() !== 'closed') {
                const [open, close] = dayInfo.hours.split(' - ');
                hoursState[day] = { open, close };
            } else {
                hoursState[day] = { open: 'closed', close: '' };
            }
        });
        setOpeningHours(hoursState);
    } else if (!isBusinessLoading && !business) {
      notFound();
    }
  }, [business, categories, allCountries, allCities, isBusinessLoading]);
  
  useEffect(() => {
    if (selectedCountryId && allCities) {
      setAvailableCities(allCities.filter(city => city.countryId === selectedCountryId));
    } else {
      setAvailableCities([]);
    }
  }, [selectedCountryId, allCities]);

  const handleHourChange = (day: string, type: 'open' | 'close', value: string) => {
    setOpeningHours(prev => {
        if (!prev) return null;
        const newHours = { ...prev[day], [type]: value };
        if (type === 'open' && value === 'closed') {
            newHours.close = '';
        }
        return {
            ...prev,
            [day]: newHours
        };
    });
};


  const handleCategoryChange = (categoryId: string, currentServices?: string[]) => {
    const category = categories?.find(c => c.id === categoryId);
    if (category) {
      setSelectedCategory(category.name);
      setAvailableServices(servicesByCategory[category.name] || []);
      if(currentServices) {
          setSelectedServices(currentServices);
      }
    } else {
      setSelectedCategory('');
      setAvailableServices([]);
    }
  };

  const handleCountryChange = (countryId: string) => {
    setSelectedCountryId(countryId);
  };
  
  const handleAddSocialLink = () => {
    if (selectedSocialPlatform && !socialLinks.some(l => l.platform === selectedSocialPlatform)) {
      setSocialLinks([...socialLinks, { platform: selectedSocialPlatform, link: '', id: nextSocialId }]);
      setNextSocialId(nextSocialId + 1);
    }
  };

  const handleRemoveSocialLink = (id: number) => {
    setSocialLinks(socialLinks.filter(link => link.id !== id));
  };

  const handleSocialLinkChange = (id: number, value: string) => {
    setSocialLinks(socialLinks.map(link => link.id === id ? { ...link, link: value } : link));
  };


  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!firestore || !businessDocRef) return;

    const formData = new FormData(e.currentTarget);
    const businessName = formData.get('business-name') as string;
    
    // In a real app, you would collect all form data and build an update object
    const updateData = {
        name: businessName,
        isFeatured: isFeatured,
        // ... collect other fields
    };

    updateDocumentNonBlocking(businessDocRef, updateData);

    toast({
      title: 'Business Updated!',
      description: `The business "${businessName}" has been saved.`,
    });

    router.push('/admin/businesses');
  };

  if (isBusinessLoading || !business || !openingHours || !categories) {
    return (
        <div className="mx-auto grid max-w-2xl flex-1 auto-rows-max gap-4">
            <h1 className="text-xl font-semibold">Loading...</h1>
        </div>
    );
  }

  return (
    <div className="mx-auto grid max-w-2xl flex-1 auto-rows-max gap-4">
        <div className="flex items-center gap-4">
            <Button variant="outline" size="icon" className="h-7 w-7" asChild>
                <Link href="/admin/businesses">
                    <ChevronLeft className="h-4 w-4" />
                    <span className="sr-only">Back</span>
                </Link>
            </Button>
            <h1 className="flex-1 shrink-0 whitespace-nowrap text-xl font-semibold tracking-tight sm:grow-0">
                Edit: {business.name}
            </h1>
        </div>
        <form onSubmit={handleSubmit} className="grid gap-4">
            <Card>
                <CardHeader>
                    <CardTitle>Business Details</CardTitle>
                    <CardDescription>Update the details for the business.</CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                    <div className="space-y-2">
                        <Label htmlFor="business-name">Business Name</Label>
                        <Input id="business-name" name="business-name" defaultValue={business.name} required />
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="description">Description</Label>
                        <Textarea id="description" name="description" defaultValue={business.description} required />
                    </div>
                    <div className="flex items-center justify-between rounded-lg border p-4">
                        <div className="space-y-0.5">
                            <Label htmlFor="featured-switch">Manual Feature</Label>
                             <CardDescription>
                                Force this business to appear in the featured list.
                            </CardDescription>
                        </div>
                        <Switch
                            id="featured-switch"
                            checked={isFeatured}
                            onCheckedChange={setIsFeatured}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="category">Category</Label>
                        <Select name="category" onValueChange={handleCategoryChange} defaultValue={categories.find(c=> c.name === business.category)?.id} required>
                            <SelectTrigger id="category">
                                <SelectValue placeholder="Select a category" />
                            </SelectTrigger>
                            <SelectContent>
                                {categories.map(category => (
                                    <SelectItem key={category.id} value={category.id}>{category.name}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>
                    {selectedCategory && (
                        <div className="space-y-4 rounded-md border p-4">
                            <Label className="font-semibold">Services for {selectedCategory}</Label>
                            <div className="grid grid-cols-2 gap-4">
                                {availableServices.length > 0 ? availableServices.map(service => (
                                    <div key={service} className="flex items-center gap-2">
                                        <Checkbox 
                                            id={`service-${service}`} 
                                            name="services" 
                                            value={service}
                                            defaultChecked={selectedServices.includes(service)}
                                        />
                                        <Label htmlFor={`service-${service}`} className="font-normal">{service}</Label>
                                    </div>
                                )) : <p className='text-sm text-muted-foreground'>No services found for this category.</p>}
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle>Location</CardTitle>
                    <CardDescription>Specify the business's location.</CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                    <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                        <div className="space-y-2">
                            <Label htmlFor="country">Country</Label>
                            <Select name="country" onValueChange={handleCountryChange} defaultValue={allCountries?.find(c => c.name === business.country)?.id} required>
                                <SelectTrigger id="country">
                                    <SelectValue placeholder="Select a country" />
                                </SelectTrigger>
                                <SelectContent>
                                    {allCountries?.map(country => (
                                        <SelectItem key={country.id} value={country.id}>{country.name}</SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                        <div className="space-y-2">
                            <Label htmlFor="city">City</Label>
                            <Select name="city" required disabled={!selectedCountryId} defaultValue={allCities?.find(c => c.name === business.address.split(',')[1]?.trim())?.id}>
                                <SelectTrigger id="city">
                                    <SelectValue placeholder={selectedCountryId ? "Select a city" : "Select country first"} />
                                </SelectTrigger>
                                <SelectContent>
                                    {availableCities.map(city => (
                                        <SelectItem key={city.id} value={city.id}>{city.name}</SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                    </div>
                     <div className="space-y-2">
                        <Label htmlFor="address">Address (Street)</Label>
                        <Input id="address" name="address" defaultValue={business.address.split(',')[0]} required />
                    </div>
                </CardContent>
            </Card>
            
            <Card>
                <CardHeader>
                    <CardTitle>Contact Information</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                        <div className="space-y-2">
                            <Label htmlFor="landline">Landline</Label>
                            <Input id="landline" name="landline" defaultValue={business.phone} />
                        </div>
                        <div className="space-y-2">
                            <Label htmlFor="whatsapp">WhatsApp</Label>
                            <Input id="whatsapp" name="whatsapp" placeholder="+15551234567" />
                        </div>
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="email">Email Address</Label>
                        <Input id="email" name="email" type="email" placeholder="contact@business.com" />
                    </div>
                     <div className="space-y-2">
                        <Label htmlFor="website">Website</Label>
                        <Input id="website" name="website" type="url" defaultValue={business.website} />
                    </div>
                    <div className="space-y-4 rounded-md border bg-muted/50 p-4">
                        <Label className="font-semibold">Social Media Profiles</Label>
                        <div className="flex items-end gap-2">
                            <div className="flex-grow space-y-2">
                                <Label htmlFor="social-platform" className="text-xs text-muted-foreground">Platform</Label>
                                <Select value={selectedSocialPlatform} onValueChange={setSelectedSocialPlatform}>
                                    <SelectTrigger id="social-platform">
                                        <SelectValue placeholder="Select a platform" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {socialMediaPlatforms.map(p => (
                                            <SelectItem key={p.id} value={p.id} disabled={socialLinks.some(l => l.platform === p.id)}>
                                                {p.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                            <Button type="button" onClick={handleAddSocialLink}>Add</Button>
                        </div>
                        <div className="space-y-3">
                            {socialLinks.map(link => (
                                <div key={link.id} className="flex items-end gap-2">
                                    <div className="flex-grow space-y-2">
                                        <Label className="text-xs text-muted-foreground">
                                            {socialMediaPlatforms.find(p => p.id === link.platform)?.name} URL
                                        </Label>
                                        <Input 
                                            name={`social-${link.platform}`}
                                            placeholder={`https://${link.platform}.com/your-profile`} 
                                            value={link.link}
                                            onChange={(e) => handleSocialLinkChange(link.id, e.target.value)}
                                            required
                                        />
                                    </div>
                                    <Button type="button" variant="ghost" size="icon" onClick={() => handleRemoveSocialLink(link.id)} className='text-destructive'>
                                        <Trash2 className="h-4 w-4" />
                                    </Button>
                                </div>
                            ))}
                        </div>
                    </div>
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle>Opening Hours</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                    {daysOfWeek.map(day => (
                        <div key={day} className="grid grid-cols-3 items-center gap-2">
                            <Label className="col-span-1">{day}</Label>
                            <div className="col-span-2 grid grid-cols-2 gap-2">
                                <Select name={`open-${day}`} value={openingHours[day].open} onValueChange={(value) => handleHourChange(day, 'open', value)}>
                                    <SelectTrigger>
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="closed">Closed</SelectItem>
                                        {timeSlots.map(slot => (
                                            <SelectItem key={`open-${day}-${slot.value}`} value={slot.value}>{slot.label}</SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                {openingHours[day].open !== 'closed' && (
                                    <Select name={`close-${day}`} value={openingHours[day].close} onValueChange={(value) => handleHourChange(day, 'close', value)}>
                                        <SelectTrigger>
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {timeSlots.map(slot => (
                                                <SelectItem key={`close-${day}-${slot.value}`} value={slot.value}>{slot.label}</SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                )}
                            </div>
                        </div>
                    ))}
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle>Business Logo</CardTitle>
                    <CardDescription>Upload a new logo to replace the current one.</CardDescription>
                </CardHeader>
                <CardContent>
                    <div className='flex items-center gap-4'>
                        <Image src={business.logoUrl} alt={business.name} width="64" height="64" className='h-16 w-16 rounded-md object-cover' />
                        <Input id="logo" name="logo" type="file" />
                    </div>
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle>Cover Image</CardTitle>
                    <CardDescription>Upload a cover image for the business profile page (e.g., PNG, JPG).</CardDescription>
                </CardHeader>
                <CardContent>
                     <div className='flex items-center gap-4'>
                        <Image src={business.coverImageUrl} alt={business.name} width="128" height="72" className='h-18 w-32 rounded-md object-cover' />
                        <Input id="cover-image" name="cover-image" type="file" accept="image/*" />
                    </div>
                </CardContent>
            </Card>

            <Button type="submit" size="lg">Save Changes</Button>
        </form>
    </div>
  );
}
