"use client"

import { useState, useEffect } from "react"
import { format, eachDayOfInterval, isSameDay } from "date-fns"
import { de, enUS } from "date-fns/locale"
import { CalendarIcon, User, Home, X, Info } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/components/ui/button"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { createBooking, deleteBooking } from "@/app/actions/booking"
import { PlanSettings } from "@/components/plan-settings"

type Booking = {
    id: number
    date: Date
    sitterName: string | null
    type: string
}

type Plan = {
    id: string
    startDate: Date
    endDate: Date
    instructions: string | null
    webhookUrl: string | null
    notifyAll: boolean
    bookings: Booking[]
}

interface PlanDashboardProps {
    plan: Plan;
    dict: any;
    settingsDict: any;
    lang: string;
}

export function PlanDashboard({ plan, dict, settingsDict, lang }: PlanDashboardProps) {
    const [selectedDate, setSelectedDate] = useState<Date | null>(null)
    const [sitterName, setSitterName] = useState("")
    const [bookingType, setBookingType] = useState<"SITTER" | "OWNER_HOME">("SITTER")
    const [isDialogOpen, setIsDialogOpen] = useState(false)
    const [isSubmitting, setIsSubmitting] = useState(false)

    const dateLocale = lang === "de" ? de : enUS

    // Load saved name from localStorage
    useEffect(() => {
        const savedName = localStorage.getItem("sitter_name")
        if (savedName) setSitterName(savedName)
    }, [])

    // Generate all days
    const days = eachDayOfInterval({
        start: new Date(plan.startDate),
        end: new Date(plan.endDate),
    })

    const handleBook = async () => {
        if (!selectedDate) return
        if (bookingType === "SITTER" && !sitterName.trim()) {
            toast.error(dict.namePlaceholder) // Could use a more specific key if needed
            return
        }

        setIsSubmitting(true)
        try {
            await createBooking(plan.id, selectedDate, bookingType === "SITTER" ? sitterName : "Owner", bookingType, lang)

            // Save name to localStorage if it's a sitter booking
            if (bookingType === "SITTER") {
                localStorage.setItem("sitter_name", sitterName)
            }

            toast.success(dict.bookedSuccess)
            setIsDialogOpen(false)
        } catch (error) {
            toast.error(dict.bookError)
        } finally {
            setIsSubmitting(false)
        }
    }

    const handleCancel = async (bookingId: number) => {
        if (!confirm(dict.cancelConfirm)) return

        try {
            await deleteBooking(bookingId, plan.id, lang)
            toast.success(dict.cancelSuccess)
        } catch {
            toast.error(dict.cancelError)
        }
    }

    return (
        <div className="space-y-4">
            <div className="flex justify-between items-center bg-muted/50 p-4 rounded-lg">
                <div className="flex items-center gap-2">
                    <h2 className="text-lg font-semibold">{dict.overview}</h2>
                    {plan.instructions && (
                        <Dialog>
                            <DialogTrigger asChild>
                                <Button variant="ghost" size="sm" className="gap-2">
                                    <Info className="w-4 h-4" />
                                    {dict.instructions}
                                </Button>
                            </DialogTrigger>
                            <DialogContent>
                                <DialogHeader>
                                    <DialogTitle>{dict.instructionsTitle}</DialogTitle>
                                </DialogHeader>
                                <div className="whitespace-pre-wrap">{plan.instructions}</div>
                            </DialogContent>
                        </Dialog>
                    )}
                </div>
                <div className="flex gap-2">
                    <Button variant="outline" size="sm" asChild>
                        <a href={`/api/plan/${plan.id}/ics`} target="_blank" rel="noopener noreferrer">
                            <CalendarIcon className="w-4 h-4 mr-2" />
                            {dict.export}
                        </a>
                    </Button>
                    <PlanSettings
                        planId={plan.id}
                        initialWebhookUrl={plan.webhookUrl}
                        initialInstructions={plan.instructions}
                        initialNotifyAll={plan.notifyAll}
                        dict={settingsDict}
                        lang={lang}
                    />
                </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {days.map((day) => {
                    const booking = plan.bookings.find((b) => isSameDay(new Date(b.date), day))
                    const isOwnerHome = booking?.type === "OWNER_HOME"

                    return (
                        <div
                            key={day.toISOString()}
                            className={`p-4 border rounded-lg flex flex-col justify-between transition-colors ${booking
                                ? isOwnerHome
                                    ? "bg-blue-50 dark:bg-blue-900/20 border-blue-200"
                                    : "bg-green-50 dark:bg-green-900/20 border-green-200"
                                : "bg-card hover:bg-accent/50"
                                }`}
                        >
                            <div className="flex justify-between items-start mb-2">
                                <div className="font-semibold flex items-center gap-2">
                                    <CalendarIcon className="w-4 h-4 opacity-70" />
                                    {format(day, "PPPP", { locale: dateLocale })}
                                </div>
                                {booking && (
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-6 w-6 -mr-2 -mt-2 opacity-50 hover:opacity-100 text-destructive"
                                        onClick={() => handleCancel(booking.id)}
                                    >
                                        <X className="w-4 h-4" />
                                        <span className="sr-only">Remove</span>
                                    </Button>
                                )}
                            </div>

                            {booking ? (
                                <div className="flex items-center gap-2">
                                    {isOwnerHome ? (
                                        <>
                                            <Home className="w-5 h-5 text-blue-500" />
                                            <span className="font-medium text-blue-700 dark:text-blue-300">{dict.ownerHome}</span>
                                        </>
                                    ) : (
                                        <>
                                            <User className="w-5 h-5 text-green-600" />
                                            <span className="font-medium text-green-700 dark:text-green-300">{booking.sitterName}</span>
                                        </>
                                    )}
                                </div>
                            ) : (
                                <Dialog open={isDialogOpen && isSameDay(selectedDate!, day)} onOpenChange={(open: boolean) => {
                                    setIsDialogOpen(open)
                                    if (open) setSelectedDate(day)
                                    else setSelectedDate(null)
                                }}>
                                    <DialogTrigger asChild>
                                        <Button variant="outline" className="w-full dashed border-2">{dict.illDoIt}</Button>
                                    </DialogTrigger>
                                    <DialogContent>
                                        <DialogHeader>
                                            <DialogTitle>{dict.bookTitle.replace("{date}", format(day, "PPP", { locale: dateLocale }))}</DialogTitle>
                                            <DialogDescription>
                                                {dict.bookDesc}
                                            </DialogDescription>
                                        </DialogHeader>

                                        <div className="grid gap-4 py-4">
                                            <RadioGroup value={bookingType} onValueChange={(v: any) => setBookingType(v)} className="flex gap-4">
                                                <div className="flex items-center space-x-2">
                                                    <RadioGroupItem value="SITTER" id="r1" />
                                                    <Label htmlFor="r1">{dict.imSitting}</Label>
                                                </div>
                                                <div className="flex items-center space-x-2">
                                                    <RadioGroupItem value="OWNER_HOME" id="r2" />
                                                    <Label htmlFor="r2">{dict.ownerIsHome}</Label>
                                                </div>
                                            </RadioGroup>

                                            {bookingType === "SITTER" && (
                                                <div className="grid gap-2">
                                                    <Label htmlFor="name">{dict.nameLabel}</Label>
                                                    <Input
                                                        id="name"
                                                        value={sitterName}
                                                        onChange={(e) => setSitterName(e.target.value)}
                                                        placeholder={dict.namePlaceholder}
                                                        autoFocus
                                                    />
                                                </div>
                                            )}
                                        </div>

                                        <DialogFooter>
                                            <Button onClick={handleBook} disabled={isSubmitting}>
                                                {isSubmitting ? dict.saving : dict.confirmBooking}
                                            </Button>
                                        </DialogFooter>
                                    </DialogContent>
                                </Dialog>
                            )}
                        </div>
                    )
                })}
            </div>
        </div>
    )
}
