"use client"
import React from "react"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { useRescheduleAppointment } from "@/lib/react-query/hooks/appointments"
import { useGetStylistsByService, useGetStylistById } from "@/lib/react-query/hooks/stylists"
import { useGetOffersByClientId } from "@/lib/react-query/hooks/offers"
import type { CreateBookingPayload } from "@/types/bookings"
import { BookingDateTimeFields } from "./BookingDateTimeFields"
import { Autocomplete } from "@/components/common/Autocomplete"
import { useToaster } from "@/context/ToasterContext"
import { TimeSuggestions } from "./TimeSuggestions"
import { useTranslations } from "next-intl"
import { useAuth } from "@/context/AuthContext"
import { transformAvailabilityToSuggestions } from "@/lib/utils"

interface Appointment {
    id: number
    bookingId: string
    staffId: number
    date: Date
    startTime: string
    endTime: string
    clientName: string
    service: string
    status: string
    color: "cyan" | "orange" | "teal" | "pink"
    serviceId?: string
    salonId?: string
    realStylistId?: string
    clientId?: string
    offerId?: string
}

interface FullEditBookingModalProps {
    open: boolean
    setOpen: (open: boolean) => void
    appointment: Appointment | null
    services?: { value: string; label: string; description: string }[]
    clients?: { value: string; label: string; description: string }[]
    onSuccess?: () => void
}

export default function FullEditBookingModal({ open, setOpen, appointment, services, clients, onSuccess }: FullEditBookingModalProps) {
    const rescheduleAppointmentMutation = useRescheduleAppointment()
    const toast = useToaster()
    const t = useTranslations()
    const { user } = useAuth()

    const bookingSchema = z.object({
        serviceId: z.string().min(1, t("calendar.validation.serviceRequired")),
        clientId: z.string().min(1, t("calendar.validation.clientRequired")),
        stylistId: z.string().optional(),
        offerId: z.string().optional()
    })

    const form = useForm({
        resolver: zodResolver(bookingSchema),
        defaultValues: {
            serviceId: "",
            clientId: "",
            stylistId: "",
            offerId: ""
        }
    })

    const [dateTimeFields, setDateTimeFields] = React.useState<{
        date: Date | undefined
        startTime: string
    }>({
        date: undefined,
        startTime: ""
    })

    // Prefill form when appointment changes
    React.useEffect(() => {
        if (appointment && open) {
            form.reset({
                serviceId: appointment.serviceId || "",
                clientId: appointment.clientId || "",
                stylistId: appointment.realStylistId || "",
                offerId: appointment.offerId || ""
            })

            // Extract local time (HH:mm) from the ISO string if it's in ISO format
            let formattedTime = appointment.startTime
            if (appointment.startTime.includes('T')) {
                const startDate = new Date(appointment.startTime)
                if (!isNaN(startDate.getTime())) {
                    formattedTime = `${startDate.getHours().toString().padStart(2, "0")}:${startDate.getMinutes().toString().padStart(2, "0")}`
                }
            }

            setDateTimeFields({
                date: appointment.date,
                startTime: formattedTime
            })
        }
    }, [appointment, open, form])

    const watchedServiceId = form.watch("serviceId")
    const watchedClientId = form.watch("clientId")
    const watchedStylistId = form.watch("stylistId") || ""
    const { data: stylistsData, isLoading: isLoadingStylists } = useGetStylistsByService(watchedServiceId)
    const { data: offersData } = useGetOffersByClientId(watchedClientId)
    const { data: stylistDetail } = useGetStylistById(watchedStylistId)

    const offerOptions = React.useMemo(() => {
        return offersData?.offers?.map(offer => ({
            value: offer._id,
            label: offer.title,
            description: `${offer.discountValue}${offer.discountType === 'percentage' ? '%' : '€'} off`
        })) || []
    }, [offersData])

    const stylistOptions = React.useMemo(() => {
        return stylistsData?.map(stylist => ({
            value: stylist._id,
            label: stylist.name,
            description: stylist.role || ""
        })) || []
    }, [stylistsData])

    const [dateTimeError, setDateTimeError] = React.useState<string>("")
    const [timeSuggestions, setTimeSuggestions] = React.useState<{
        message: string
        suggestions: any[]
    } | null>(null)

    const handleSelectSuggestedTime = (date: Date, startTime: string, stylistId: string) => {
        setDateTimeFields({ date, startTime })
        if (stylistId) {
            form.setValue("stylistId", stylistId)
        }
        setTimeSuggestions(null)
        setDateTimeError("")
    }

    const handleCancelSuggestions = () => {
        setTimeSuggestions(null)
    }

    function onSubmit(data: { serviceId: string; clientId: string; stylistId?: string; offerId?: string }) {
        if (!appointment) return

        if (!dateTimeFields.date || !dateTimeFields.startTime) {
            setDateTimeError(t("calendar.validation.selectDateTime"))
            return
        }
        setDateTimeError("")

        const bookingData: CreateBookingPayload = {
            serviceId: data.serviceId,
            clientId: data.clientId,
            requestedStart: {
                date: `${dateTimeFields.date.getFullYear()}-${String(dateTimeFields.date.getMonth() + 1).padStart(2, "0")}-${String(dateTimeFields.date.getDate()).padStart(2, "0")}`,
                time: dateTimeFields.startTime
            }
        }

        if (data.stylistId) {
            bookingData.stylistId = data.stylistId
        }

        if (data.offerId) {
            bookingData.offerId = data.offerId
        }

        rescheduleAppointmentMutation.mutate({
            oldId: appointment.bookingId,
            payload: bookingData
        }, {
            onSuccess: (response) => {
                if (response?.suggestions) {
                    const message = response.message || t("calendar.timeSuggestions.description")
                    toast.showInfo(message)
                    setTimeSuggestions({ message, suggestions: response.suggestions })
                    return
                }
                toast.showSuccess(t("calendar.modals.bookingUpdatedSuccessfully"))
                setOpen(false)
                onSuccess?.()
            },
            onError: (error: any) => {
                const data = error.response?.data
                if (data?.reason === "SLOT_NOT_AVAILABLE" && data?.availability) {
                    const suggestions = transformAvailabilityToSuggestions(data.availability)
                    setTimeSuggestions({
                        message: t("calendar.timeSuggestions.description"),
                        suggestions
                    })
                    return
                }
            }
        })
    }

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogContent className="w-[95vw] sm:max-w-[689px] bg-white border-0 max-h-[90vh] overflow-y-auto overflow-x-hidden [&>button]:top-5 [&>button]:right-5 [&>button]:text-white [&>button]:hover:text-gray-200 [&>button>svg]:stroke-[4px]">
                <DialogHeader className="bg-primary-gradient -m-6 mb-0 px-6 py-3 rounded-t-lg">
                    <DialogTitle className="text-white text-lg font-medium">{t("calendar.modals.editBooking")}</DialogTitle>
                </DialogHeader>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="overflow-y-auto px-1 max-h-[70vh]">
                        <div className="space-y-4">
                            <div className="grid grid-cols-2 gap-4 mt-4">
                                <div className="group">
                                    <FormField
                                        name="clientId"
                                        control={form.control}
                                        render={({ field, fieldState }) => (
                                            <FormItem>
                                                <FormLabel className="group-focus-within:text-primary-blue">{t("calendar.form.client")}</FormLabel>
                                                <FormControl>
                                                    <Autocomplete
                                                        options={clients || []}
                                                        value={field.value}
                                                        onChange={field.onChange}
                                                        placeholder={t("calendar.form.selectClient")}
                                                        searchPlaceholder={t("calendar.form.searchClients")}
                                                        emptyMessage={t("calendar.form.noClientsFound")}
                                                        className={fieldState.invalid ? "border-red-500 focus:border-red-500 focus:ring-2 focus:ring-red-200" : ""}
                                                        required
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>
                                <div className="group">
                                    <FormField
                                        name="serviceId"
                                        control={form.control}
                                        render={({ field, fieldState }) => (
                                            <FormItem>
                                                <FormLabel className="group-focus-within:text-primary-blue">{t("calendar.form.service")}</FormLabel>
                                                <FormControl>
                                                    <Autocomplete
                                                        options={services || []}
                                                        value={field.value}
                                                        onChange={field.onChange}
                                                        placeholder={t("calendar.form.selectService")}
                                                        searchPlaceholder={t("calendar.form.searchServices")}
                                                        emptyMessage={t("calendar.form.noServicesFound")}
                                                        className={fieldState.invalid ? "border-red-500 focus:border-red-500 focus:ring-2 focus:ring-red-200" : ""}
                                                        required
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                <div className="group">
                                    <FormField
                                        name="stylistId"
                                        control={form.control}
                                        render={({ field, fieldState }) => (
                                            <FormItem>
                                                <FormLabel className="group-focus-within:text-primary-blue">{t("calendar.form.stylist")}</FormLabel>
                                                <FormControl>
                                                    <Autocomplete
                                                        options={stylistOptions}
                                                        value={field.value}
                                                        onChange={field.onChange}
                                                        placeholder={t("calendar.form.selectStylist")}
                                                        searchPlaceholder={t("calendar.form.searchStylists")}
                                                        emptyMessage={watchedServiceId ? t("calendar.form.noStylistsFound") : t("calendar.form.selectServiceFirst")}
                                                        className={fieldState.invalid ? "border-red-500 focus:border-red-500 focus:ring-2 focus:ring-red-200" : ""}
                                                        disabled={!watchedServiceId || isLoadingStylists}
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>
                                <div className="group">
                                    <FormField
                                        name="offerId"
                                        control={form.control}
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel className="group-focus-within:text-primary-blue">{t("calendar.form.offer")}</FormLabel>
                                                <FormControl>
                                                    <Autocomplete
                                                        options={offerOptions}
                                                        value={field.value}
                                                        onChange={field.onChange}
                                                        placeholder={t("calendar.form.selectOffer")}
                                                        searchPlaceholder={t("calendar.form.searchOffers")}
                                                        emptyMessage={watchedClientId ? t("calendar.form.noOffersFound") : t("calendar.form.selectClientFirst")}
                                                        disabled={!watchedClientId}
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>
                            </div>

                            {/* Stats Box */}
                            {watchedClientId && (
                                <div className="bg-blue-50/50 rounded-lg p-3 flex justify-around items-center border border-blue-100">
                                    <div className="text-center flex-1">
                                        <p className="text-[11px] uppercase text-gray-500 font-medium tracking-wider mb-1">Total Spend</p>
                                        <p className="text-xl font-bold text-blue-950">€{offersData?.stats?.totalSpend || 0}</p>
                                    </div>
                                    <div className="h-10 w-[1px] bg-blue-200 flex-none mx-4"></div>
                                    <div className="text-center flex-1">
                                        <p className="text-[11px] uppercase text-gray-500 font-medium tracking-wider mb-1">Appointments</p>
                                        <p className="text-xl font-bold text-blue-950">{offersData?.stats?.appointmentCount || 0}</p>
                                    </div>
                                </div>
                            )}

                            <BookingDateTimeFields
                                value={dateTimeFields}
                                onChange={setDateTimeFields}
                                dateError={dateTimeError && !dateTimeFields.date ? dateTimeError : undefined}
                                workingHours={stylistDetail?.workingHours}
                                vacations={stylistDetail?.vacations}
                                stylistName={stylistDetail?.name}
                            />

                            {timeSuggestions && (
                                <div className="border-t pt-4">
                                    <TimeSuggestions
                                        suggestions={timeSuggestions.suggestions}
                                        onSelectTime={handleSelectSuggestedTime}
                                        onCancel={handleCancelSuggestions}
                                        stylists={stylistOptions}
                                    />
                                </div>
                            )}

                            <DialogFooter className="flex justify-end w-full mt-4">
                                <div className="flex gap-4 mt-2">
                                    <Button
                                        variant="outline"
                                        type="button"
                                        onClick={() => setOpen(false)}
                                        className="flex-1 bg-transparent border-blue-950 text-blue-950 rounded-sm px-8"
                                    >
                                        {t("calendar.buttons.cancel")}
                                    </Button>
                                    <Button
                                        type="submit"
                                        className="flex-1 bg-primary-gradient text-white rounded-sm px-8"
                                        disabled={rescheduleAppointmentMutation.isPending}
                                    >
                                        {rescheduleAppointmentMutation.isPending ? t("calendar.buttons.updating") : t("calendar.buttons.updateBooking")}
                                    </Button>
                                </div>
                            </DialogFooter>
                        </div>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    )
}
