
'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 } from 'next/navigation';
import { useState, useEffect } from 'react';
import { Checkbox } from '@/components/ui/checkbox';
import { useFirestore, useUser, useCollection, useMemoFirebase } from '@/firebase';
import { addDocumentNonBlocking } from '@/firebase/non-blocking-updates';
import { collection, serverTimestamp, getDocs } from 'firebase/firestore';
import type { Category, Country, City } from '@/lib/types';
import { servicesByCategory } from '@/lib/data';

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 AddBusinessPage() {
  const { toast } = useToast();
  const router = useRouter();
  const firestore = useFirestore();
  const { user } = useUser();

  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);

  useEffect(() => {
    if (selectedCountryId && allCities) {
      setAvailableCities(allCities.filter(city => city.countryId === selectedCountryId));
    } else {
      setAvailableCities([]);
    }
  }, [selectedCountryId, allCities]);


  const initialHours = daysOfWeek.reduce((acc, day) => {
    acc[day] = { open: '09:00', close: '17:00' };
    return acc;
  }, {} as OpeningHoursState);
  initialHours['Saturday'] = { open: '10:00', close: '14:00' };
  initialHours['Sunday'] = { open: 'closed', close: '' };
  
  const [openingHours, setOpeningHours] = useState<OpeningHoursState>(initialHours);

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

  const handleCategoryChange = (categoryId: string) => {
    const category = categories?.find(c => c.id === categoryId);
    if (category) {
      setSelectedCategory(category.name);
      setAvailableServices(servicesByCategory[category.name] || []);
    } 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 (!user || !firestore) {
        toast({ title: 'Error', description: 'User not logged in or database not available.' });
        return;
    }

    const formData = new FormData(e.currentTarget);
    const businessName = formData.get('business-name') as string;
    const slug = businessName.toLowerCase().replace(/\s+/g, '-');
    const categoryName = categories?.find(c => c.id === formData.get('category'))?.name || '';
    const countryName = allCountries?.find(c => c.id === formData.get('country'))?.name || '';
    const cityName = allCities?.find(c => c.id === formData.get('city'))?.name || '';
    
    const openingHoursFormatted = daysOfWeek.map(day => {
        const hours = openingHours[day];
        const time = hours.open === 'closed' ? 'Closed' : `${hours.open} - ${hours.close}`;
        return { day, hours: time };
    });

    const newBusiness = {
        name: businessName,
        slug: slug,
        description: formData.get('description') as string,
        category: categoryName,
        services: formData.getAll('services') as string[],
        address: `${formData.get('address') as string}, ${cityName}`,
        country: countryName,
        phone: formData.get('landline') as string,
        website: formData.get('website') as string,
        openingHours: openingHoursFormatted,
        logoUrl: 'https://picsum.photos/seed/new-business-logo/200/200',
        coverImageUrl: 'https://picsum.photos/seed/new-business-cover/1200/400',
        imageHint: 'business place',
        rating: 0,
        reviewCount: 0,
        coords: { lat: 0, lng: 0 }, // Placeholder coords
        status: 'pending',
        createdBy: user.uid,
        createdAt: serverTimestamp()
    };

    addDocumentNonBlocking(collection(firestore, 'businesses'), newBusiness);

    toast({
      title: 'Business Submitted for Review!',
      description: `Your business "${businessName}" has been sent to our team for approval.`,
    });

    router.push('/reviews');
  };

  if (!user) {
    return (
        <div className="container mx-auto max-w-2xl px-4 py-12 text-center">
            <h1 className="text-2xl font-bold">Please Log In</h1>
            <p className="mt-2 text-muted-foreground">You need to be logged in to add a business.</p>
            <Button asChild className="mt-6">
                <Link href="/login">Login</Link>
            </Button>
        </div>
    );
  }

  return (
    <div className="container mx-auto max-w-2xl px-4 py-6 sm:px-6 lg:px-8">
        <div className="mb-4 flex items-center gap-4">
            <Button variant="outline" size="icon" className="h-7 w-7" asChild>
                <Link href="/reviews">
                    <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">
            Add Your Business
            </h1>
        </div>
        <form onSubmit={handleSubmit} className="grid gap-4">
            <Card>
                <CardHeader>
                    <CardTitle>Business Details</CardTitle>
                    <CardDescription>Fill in the details for your new 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" placeholder="e.g. The Corner Bistro" required />
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="description">Description</Label>
                        <Textarea id="description" name="description" placeholder="Describe your business..." required />
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="category">Category</Label>
                        <Select name="category" onValueChange={handleCategoryChange} 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} />
                                        <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 your 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} 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}>
                                <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" placeholder="e.g. 123 Main Street" 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" placeholder="(555) 123-4567" />
                        </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" placeholder="https://www.business.com" />
                    </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 logo for your business profile (e.g., PNG, JPG).</CardDescription>
                </CardHeader>
                <CardContent>
                    <Input id="logo" name="logo" type="file" />
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle>Cover Image</CardTitle>
                    <CardDescription>Upload a cover image for your business profile page (e.g., PNG, JPG).</CardDescription>
                </CardHeader>
                <CardContent>
                    <Input id="cover-image" name="cover-image" type="file" accept="image/*" />
                </CardContent>
            </Card>

            <Button type="submit" size="lg">Submit for Review</Button>
        </form>
    </div>
  );
}
