"use client"

import { useEffect, useRef, useState } from "react"
import { useForm, useFieldArray, Controller } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { useTranslations } from "next-intl"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Switch } from "@/components/ui/switch"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Plus, Trash2, Globe, MapPin, Instagram, Facebook, Phone, Calendar, Info, Link as LinkIcon, Clock, ChevronDown, Copy } from "lucide-react"
import { useUpdateProfileInfo } from "@/lib/react-query/hooks/auth"
import type { User } from "@/types/auth"
import { TimeInput } from "@/components/common/TimeInput"
import { WorkingHoursForm, DaySchedule } from "@/components/common/WorkingHoursForm"

const profileSchema = z.object({
    owner_name: z.string(),
    website: z.string().url("Invalid URL").or(z.literal("")),
    address: z.string().min(1, "Address is required"),
    social_links: z.object({
        instagram: z.string().url("Invalid URL").or(z.literal("")).optional(),
        facebook: z.string().url("Invalid URL").or(z.literal("")).optional(),
        google: z.string().url("Invalid URL").or(z.literal("")).optional(),
        tiktok: z.string().url("Invalid URL").or(z.literal("")).optional(),
    }),
    opening_hours: z.record(z.string(), z.object({
        enabled: z.boolean(),
        timeSlots: z.array(z.object({
            start: z.string(),
            end: z.string(),
        }))
    })),
    holidays: z.array(z.object({
        date: z.string(),
        reason: z.string().min(1, "Reason is required"),
    })),
})

type ProfileFormValues = z.infer<typeof profileSchema>

interface EditProfileModalProps {
    user: User
    isOpen: boolean
    onClose: () => void
}

const DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

export const EditProfileModal = ({ user, isOpen, onClose }: EditProfileModalProps) => {
    const t = useTranslations("profile")
    const tCommon = useTranslations("common")
    const tStaff = useTranslations("staff")
    const tWHF = useTranslations("workingHoursForm")
    const updateProfile = useUpdateProfileInfo()

    const form = useForm<ProfileFormValues>({
        resolver: zodResolver(profileSchema),
        defaultValues: {
            owner_name: user.owner_name || "",
            website: user.website || "",
            address: user.address || "",
            social_links: {
                instagram: user.social_links?.instagram || "",
                facebook: user.social_links?.facebook || "",
                google: user.social_links?.google || "",
                tiktok: user.social_links?.tiktok || "",
            },
            opening_hours: DAYS.reduce((acc, day) => {
                const dayKey = day.toLowerCase()
                const slots = user.opening_hours?.filter(oh => oh.day.toLowerCase() === dayKey) || []
                acc[dayKey] = {
                    enabled: slots.length > 0 ? !slots.every(s => s.closed) : true,
                    timeSlots: slots.length > 0 && !slots.every(s => s.closed)
                        ? slots.map(s => ({ start: s.open, end: s.close }))
                        : [{ start: "09:00", end: "21:00" }]
                }
                return acc
            }, {} as Record<string, DaySchedule>),
            holidays: user.holidays?.map(h => ({
                date: h.date.split("T")[0],
                reason: h.reason,
            })) || [],
        },
    })

    const { register, control, handleSubmit, reset, watch, setValue, formState: { errors } } = form

    const [addressPredictions, setAddressPredictions] = useState<any[]>([])
    const [showAddressDropdown, setShowAddressDropdown] = useState(false)
    const autocompleteService = useRef<any>(null)
    const dropdownRef = useRef<HTMLDivElement>(null)

    useEffect(() => {
        const checkGoogle = () => {
            if (typeof window !== "undefined" && (window as any).google && (window as any).google.maps && (window as any).google.maps.places) {
                if (!autocompleteService.current) {
                    autocompleteService.current = new (window as any).google.maps.places.AutocompleteService()
                }
                return true
            }
            return false
        }

        if (!checkGoogle()) {
            const interval = setInterval(() => {
                if (checkGoogle()) {
                    clearInterval(interval)
                }
            }, 500)
            return () => clearInterval(interval)
        }
    }, [])

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setShowAddressDropdown(false)
            }
        }
        document.addEventListener("mousedown", handleClickOutside)
        return () => document.removeEventListener("mousedown", handleClickOutside)
    }, [])

    const handleAddressInput = (val: string) => {
        setValue("address", val)
        if (!val || val.length < 3) {
            setAddressPredictions([])
            setShowAddressDropdown(false)
            return
        }

        if (!autocompleteService.current && typeof window !== "undefined" && (window as any).google?.maps?.places) {
            autocompleteService.current = new (window as any).google.maps.places.AutocompleteService()
        }

        if (autocompleteService.current) {
            autocompleteService.current.getPlacePredictions(
                { input: val, types: ["address"] },
                (predictions: any[] | null) => {
                    if (predictions) {
                        setAddressPredictions(predictions)
                        setShowAddressDropdown(true)
                    } else {
                        setAddressPredictions([])
                        setShowAddressDropdown(false)
                    }
                }
            )
        }
    }

    useEffect(() => {
        if (isOpen) {
            reset({
                owner_name: user.owner_name || "",
                website: user.website || "",
                address: user.address || "",
                social_links: {
                    instagram: user.social_links?.instagram || "",
                    facebook: user.social_links?.facebook || "",
                    google: user.social_links?.google || "",
                    tiktok: user.social_links?.tiktok || "",
                },
                opening_hours: DAYS.reduce((acc, day) => {
                    const dayKey = day.toLowerCase()
                    const slots = user.opening_hours?.filter(oh => oh.day.toLowerCase() === dayKey) || []
                    acc[dayKey] = {
                        enabled: slots.length > 0 ? !slots.every(s => s.closed) : true,
                        timeSlots: slots.length > 0 && !slots.every(s => s.closed)
                            ? slots.map(s => ({ start: s.open, end: s.close }))
                            : [{ start: "09:00", end: "21:00" }]
                    }
                    return acc
                }, {} as Record<string, DaySchedule>),
                holidays: user.holidays?.map(h => ({
                    date: new Date(h.date).toISOString().split('T')[0],
                    reason: h.reason,
                })) || [],
            })
        }
    }, [isOpen, user, reset])

    // ohFields is no longer used directly since we use WorkingHoursForm with a single controller field
    // but the opening_hours field still exists in the form state as a Record


    const { fields: holidayFields, append: appendHoliday, remove: removeHoliday } = useFieldArray({
        control,
        name: "holidays",
    })

    const onSubmit = (data: ProfileFormValues) => {
        // Flatten the opening_hours record back into the array format expected by the API
        const flattenedOpeningHours: any[] = []
            ; (Object.entries(data.opening_hours) as [string, any][]).forEach(([day, schedule]) => {
                const dayName = day.charAt(0).toUpperCase() + day.slice(1)
                if (!schedule.enabled) {
                    flattenedOpeningHours.push({
                        day: dayName,
                        open: "09:00",
                        close: "18:00",
                        closed: true
                    })
                } else {
                    schedule.timeSlots.forEach((slot: any) => {
                        flattenedOpeningHours.push({
                            day: dayName,
                            open: slot.start,
                            close: slot.end,
                            closed: false
                        })
                    })
                }
            })

        const payload = {
            ...data,
            opening_hours: flattenedOpeningHours
        }

        updateProfile.mutate(payload, {
            onSuccess: () => {
                onClose()
            },
        })
    }

    return (
        <Dialog open={isOpen} onOpenChange={onClose}>
            <DialogContent className="max-w-4xl h-[80vh] flex flex-col p-0 overflow-hidden bg-white border-0 [&>button]:top-4 [&>button]:right-4 [&>button]:text-white [&>button]:hover:text-gray-200">
                <DialogHeader className="bg-primary-gradient px-6 py-4 rounded-t-lg">
                    <DialogTitle className="text-white text-xl font-semibold">{t("editProfile")}</DialogTitle>
                    <DialogDescription className="text-blue-50/80">{t("editProfileDesc")}</DialogDescription>
                </DialogHeader>

                <Form {...form}>
                    <form onSubmit={handleSubmit(onSubmit)} className="flex-1 flex flex-col min-h-0 overflow-hidden">
                        <Tabs defaultValue="general" className="flex-1 flex flex-col min-h-0 overflow-hidden">
                            <div className="px-6 py-4 shrink-0 overflow-x-auto no-scrollbar">
                                <TabsList className="w-max flex h-11 items-center justify-start bg-gray-100/80 p-1 rounded-xl gap-1">
                                    <TabsTrigger value="general" className="rounded-lg h-full px-4 text-sm font-semibold flex items-center gap-2 transition-all data-[state=active]:bg-blue-950 data-[state=active]:text-white text-gray-600 data-[state=inactive]:hover:bg-gray-200 border-none">
                                        <Info className="w-4 h-4" />
                                        {t("businessInformation")}
                                    </TabsTrigger>

                                    <TabsTrigger value="social" className="rounded-lg h-full px-4 text-sm font-semibold flex items-center gap-2 transition-all data-[state=active]:bg-blue-950 data-[state=active]:text-white text-gray-600 data-[state=inactive]:hover:bg-gray-200 border-none">
                                        <LinkIcon className="w-4 h-4" />
                                        {t("socialLinks")}
                                    </TabsTrigger>
                                    <TabsTrigger value="hours" className="rounded-lg h-full px-4 text-sm font-semibold flex items-center gap-2 transition-all data-[state=active]:bg-blue-950 data-[state=active]:text-white text-gray-600 data-[state=inactive]:hover:bg-gray-200 border-none">
                                        <Clock className="w-4 h-4" />
                                        {t("openingHours")}
                                    </TabsTrigger>
                                    <TabsTrigger value="holidays" className="rounded-lg h-full px-4 text-sm font-semibold flex items-center gap-2 transition-all data-[state=active]:bg-blue-950 data-[state=active]:text-white text-gray-600 data-[state=inactive]:hover:bg-gray-200 border-none">
                                        <Calendar className="w-4 h-4" />
                                        {t("holidays")}
                                    </TabsTrigger>
                                </TabsList>
                            </div>

                            <ScrollArea className="flex-1 min-h-0">
                                <div className="p-6">
                                    {/* General Tab */}
                                    <TabsContent value="general" className="space-y-4 m-0">
                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                            <div className="space-y-2">
                                                <Label className="text-sm font-semibold text-gray-700">{t("ownerName")}</Label>
                                                <Input {...register("owner_name")} placeholder="John Doe" className="border-gray-200 focus:border-blue-500" />
                                                {errors.owner_name && <p className="text-xs text-red-500 font-medium">{errors.owner_name.message}</p>}
                                            </div>
                                            <div className="space-y-2">
                                                <Label className="text-sm font-semibold text-gray-700">{t("website")}</Label>
                                                <Input {...register("website")} placeholder="https://example.com" className="border-gray-200 focus:border-blue-500" />
                                                {errors.website && <p className="text-xs text-red-500 font-medium">{errors.website.message}</p>}
                                            </div>
                                        </div>


                                        {/* Address Tab Content Moved to General */}
                                        {/* Additional fields for General Tab */}
                                        <div className="space-y-4 m-0 mt-6">
                                            <div className="space-y-4 max-w-xl">
                                                <FormField
                                                    control={form.control}
                                                    name="address"
                                                    render={({ field }) => (
                                                        <FormItem className="space-y-2 relative" ref={dropdownRef}>
                                                            <FormLabel className="text-sm font-semibold text-gray-700">{t("address")}</FormLabel>
                                                            <FormControl>
                                                                <div className="relative">
                                                                    <Input
                                                                        {...field}
                                                                        value={watch("address")}
                                                                        onChange={(e) => handleAddressInput(e.target.value)}
                                                                        onFocus={() => {
                                                                            if (addressPredictions.length > 0) setShowAddressDropdown(true)
                                                                        }}
                                                                        placeholder={t("enterAddress")}
                                                                        className="flex h-11 w-full rounded-md border border-gray-200 bg-white px-3 py-2 text-base ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 disabled:cursor-not-allowed disabled:opacity-50"
                                                                    />
                                                                    {showAddressDropdown && addressPredictions.length > 0 && (
                                                                        <div className="absolute z-[1000] w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-xl max-h-64 overflow-y-auto py-1 animate-in fade-in zoom-in-95 duration-200">
                                                                            {addressPredictions.map((prediction) => (
                                                                                <div
                                                                                    key={prediction.place_id}
                                                                                    className="px-4 py-3 hover:bg-blue-50 cursor-pointer flex items-start gap-3 transition-colors group"
                                                                                    onClick={() => {
                                                                                        setValue("address", prediction.description)
                                                                                        setAddressPredictions([])
                                                                                        setShowAddressDropdown(false)
                                                                                    }}
                                                                                >
                                                                                    <MapPin className="w-4 h-4 text-gray-400 group-hover:text-blue-500 mt-0.5 shrink-0" />
                                                                                    <div className="flex flex-col gap-0.5">
                                                                                        <span className="text-sm font-medium text-gray-900 line-clamp-1">
                                                                                            {prediction.structured_formatting.main_text}
                                                                                        </span>
                                                                                        <span className="text-xs text-gray-500 line-clamp-1">
                                                                                            {prediction.structured_formatting.secondary_text}
                                                                                        </span>
                                                                                    </div>
                                                                                </div>
                                                                            ))}
                                                                        </div>
                                                                    )}
                                                                </div>
                                                            </FormControl>
                                                            <FormMessage />
                                                        </FormItem>
                                                    )}
                                                />
                                            </div>
                                        </div>
                                    </TabsContent>




                                    {/* Social Tab */}
                                    <TabsContent value="social" className="space-y-6 m-0">
                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                            <div className="space-y-2">
                                                <Label className="flex items-center gap-2 text-sm font-semibold text-gray-700"><Instagram className="w-4 h-4 text-purple-600" /> Instagram</Label>
                                                <Input {...register("social_links.instagram")} placeholder="https://instagram.com/..." className="border-gray-200 focus:border-blue-500" />
                                            </div>
                                            <div className="space-y-2">
                                                <Label className="flex items-center gap-2 text-sm font-semibold text-gray-700"><Facebook className="w-4 h-4 text-blue-600" /> Facebook</Label>
                                                <Input {...register("social_links.facebook")} placeholder="https://facebook.com/..." className="border-gray-200 focus:border-blue-500" />
                                            </div>
                                            <div className="space-y-2">
                                                <Label className="flex items-center gap-2 text-sm font-semibold text-gray-700"><Globe className="w-4 h-4 text-orange-600" /> Google</Label>
                                                <Input {...register("social_links.google")} placeholder="https://google.com/..." className="border-gray-200 focus:border-blue-500" />
                                            </div>
                                            <div className="space-y-2">
                                                <Label className="flex items-center gap-2 text-sm font-semibold text-gray-700">♪ TikTok</Label>
                                                <Input {...register("social_links.tiktok")} placeholder="https://tiktok.com/@..." className="border-gray-200 focus:border-blue-500" />
                                            </div>
                                        </div>
                                    </TabsContent>

                                    <TabsContent value="hours" className="flex-1 m-0">
                                        <Controller
                                            control={control}
                                            name="opening_hours"
                                            render={({ field: { value, onChange } }) => (
                                                <WorkingHoursForm
                                                    value={value as Record<string, DaySchedule>}
                                                    onChange={onChange}
                                                    className="px-0"
                                                />
                                            )}
                                        />
                                    </TabsContent>

                                    {/* Holidays Tab */}
                                    <TabsContent value="holidays" className="space-y-4 m-0">
                                        <div className="space-y-4">
                                            {holidayFields.map((field, index) => (
                                                <div key={field.id} className="flex gap-4 items-start p-5 bg-amber-50/50 rounded-2xl border border-amber-100/50 group">
                                                    <div className="flex-1 grid grid-cols-1 md:grid-cols-2 gap-4">
                                                        <div className="space-y-2">
                                                            <Label className="text-xs uppercase font-extrabold text-amber-700 tracking-wider">{t("date")}</Label>
                                                            <Input type="date" {...register(`holidays.${index}.date`)} className="bg-white border-amber-200 focus:border-amber-500 h-11" />
                                                        </div>
                                                        <div className="space-y-2">
                                                            <Label className="text-xs uppercase font-extrabold text-amber-700 tracking-wider">{t("reason")}</Label>
                                                            <Input {...register(`holidays.${index}.reason`)} placeholder="e.g. New Year" className="bg-white border-amber-200 focus:border-amber-500 h-11" />
                                                        </div>
                                                    </div>
                                                    <Button
                                                        type="button"
                                                        variant="ghost"
                                                        size="icon"
                                                        onClick={() => removeHoliday(index)}
                                                        className="text-red-400 hover:text-red-600 hover:bg-red-50 mt-6"
                                                    >
                                                        <Trash2 className="w-5 h-5" />
                                                    </Button>
                                                </div>
                                            ))}
                                            <Button
                                                type="button"
                                                variant="outline"
                                                className="w-full border-dashed border-2 py-8 hover:bg-amber-50 hover:border-amber-300 transition-all text-amber-700 font-bold gap-2"
                                                onClick={() => appendHoliday({ date: new Date().toISOString().split("T")[0], reason: "" })}
                                            >
                                                <Plus className="w-5 h-5" />
                                                {t("holidays")}
                                            </Button>
                                        </div>
                                    </TabsContent>
                                </div>
                            </ScrollArea>

                            <DialogFooter className="p-6 pt-4 border-t bg-white shrink-0 flex items-center justify-end gap-3">
                                <Button type="button" variant="outline" onClick={onClose} className="px-8 h-11 min-w-[140px] border-2 border-blue-900/10 text-blue-900 font-bold hover:bg-blue-50 transition-colors">
                                    {t("cancel")}
                                </Button>
                                <Button type="submit" disabled={updateProfile.isPending} className="px-8 h-11 min-w-[140px] bg-primary-gradient text-white font-bold shadow-lg shadow-blue-900/20 hover:opacity-90 transition-opacity">
                                    {updateProfile.isPending ? t("saving") : t("save")}
                                </Button>
                            </DialogFooter>
                        </Tabs>
                    </form>
                </Form>
            </DialogContent>
        </Dialog >
    )
}
