"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, Utensils, Trash2, Check, Share2 } 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 { Textarea } from "@/components/ui/textarea"
import { uploadImage } from "@/app/actions/upload-image"
import { Camera, Upload } from "lucide-react"

import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { createBooking, deleteBooking, completeBooking } from "@/app/actions/booking"
import { PlanSettings } from "@/components/plan-settings"

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

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

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 [isCancelDialogOpen, setIsCancelDialogOpen] = useState(false)
    const [bookingToCancel, setBookingToCancel] = useState<number | null>(null)
    const [cancelReason, setCancelReason] = useState("")
    const [isSubmitting, setIsSubmitting] = useState(false)

    // Completion Dialog State
    const [isCompleteDialogOpen, setIsCompleteDialogOpen] = useState(false)
    const [bookingToComplete, setBookingToComplete] = useState<number | null>(null)
    const [completionMessage, setCompletionMessage] = useState("")
    const [completionImage, setCompletionImage] = useState<File | null>(null)
    const [imagePreview, setImagePreview] = useState<string | null>(null)

    const handleCompleteClick = (bookingId: number) => {
        setBookingToComplete(bookingId)
        setCompletionMessage("")
        setCompletionImage(null)
        setImagePreview(null)
        setIsCompleteDialogOpen(true)
    }

    const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0]
        if (file) {
            setCompletionImage(file)
            const reader = new FileReader()
            reader.onloadend = () => {
                setImagePreview(reader.result as string)
            }
            reader.readAsDataURL(file)
        }
    }

    const handleConfirmComplete = async () => {
        if (!bookingToComplete) return

        setIsSubmitting(true)
        try {
            let imageUrl: string | undefined = undefined

            if (completionImage) {
                const formData = new FormData()
                formData.append("file", completionImage)
                formData.append("planId", plan.id)
                imageUrl = await uploadImage(formData)
            }

            await completeBooking(bookingToComplete, plan.id, lang, completionMessage, imageUrl)
            toast.success(dict.jobDone)
            setIsCompleteDialogOpen(false)
            setBookingToComplete(null)
        } catch (error) {
            console.error(error)
            toast.error(dict.bookError)
        } finally {
            setIsSubmitting(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 handleCancelClick = (bookingId: number) => {
        setBookingToCancel(bookingId)
        setCancelReason("")
        setIsCancelDialogOpen(true)
    }

    const handleConfirmCancel = async () => {
        if (!bookingToCancel) return

        setIsSubmitting(true)
        try {
            await deleteBooking(bookingToCancel, plan.id, lang, cancelReason)
            toast.success(dict.cancelSuccess)
            setIsCancelDialogOpen(false)
            setBookingToCancel(null)
        } catch {
            toast.error(dict.cancelError)
        } finally {
            setIsSubmitting(false)
        }
    }

    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}
                        initialTitle={plan.title}
                        initialWebhookUrl={plan.webhookUrl}
                        initialInstructions={plan.instructions}
                        initialNotifyAll={plan.notifyAll}
                        initialFeedingPerDay={plan.feedingPerDay}
                        initialFeedingInterval={plan.feedingInterval}
                        initialLitterInterval={plan.litterInterval}
                        dict={settingsDict}
                        lang={lang}
                    />
                    <Button variant="outline" size="sm" onClick={() => {
                        if (navigator.share) {
                            navigator.share({
                                title: plan.title,
                                text: dict.shareTitle,
                                url: window.location.href,
                            }).catch(() => {
                                // Fallback if share fails / is cancelled
                                navigator.clipboard.writeText(window.location.href)
                                toast.success(dict.copySuccess)
                            })
                        } else {
                            navigator.clipboard.writeText(window.location.href)
                            toast.success(dict.copySuccess)
                        }
                    }}>
                        <Share2 className="w-4 h-4 mr-2" />
                        {dict.share}
                    </Button>
                </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={() => handleCancelClick(booking.id)}
                                    >
                                        <X className="w-4 h-4" />
                                        <span className="sr-only">Remove</span>
                                    </Button>
                                )}
                            </div>

                            {booking ? (
                                <div className="space-y-3">
                                    <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>

                                    {booking.type === "SITTER" && (
                                        <div className="pt-1">
                                            {booking.completedAt ? (
                                                <div className="flex items-center gap-2 text-green-600 font-bold bg-green-100/50 dark:bg-green-900/30 px-3 py-1.5 rounded-full border border-green-200 dark:border-green-800 w-fit text-sm">
                                                    <Check className="w-4 h-4 stroke-[3px]" />
                                                    <span>{dict.jobDone}</span>
                                                </div>
                                            ) : (
                                                // Only show button if day is today or in the past
                                                day <= new Date() || isSameDay(day, new Date()) ? (
                                                    <Button
                                                        variant="outline"
                                                        size="sm"
                                                        className="w-full flex gap-2 items-center border-green-200 hover:bg-green-100/50 text-green-700 dark:border-green-800 dark:hover:bg-green-900/40 font-semibold"
                                                        onClick={() => handleCompleteClick(booking.id)}
                                                    >
                                                        <Check className="w-4 h-4" />
                                                        {dict.markDone}
                                                    </Button>
                                                ) : null
                                            )}
                                        </div>
                                    )}
                                </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 className="mt-3 flex flex-wrap gap-2 pt-2 border-t border-border/50">
                                {Math.floor((day.getTime() - new Date(plan.startDate).setHours(0, 0, 0, 0)) / (1000 * 60 * 60 * 24)) % plan.feedingInterval === 0 && (
                                    <div className="flex gap-1 items-center" title={`${plan.feedingPerDay}x ${dict.feeding}`}>
                                        {Array.from({ length: plan.feedingPerDay }).map((_, i) => (
                                            <Utensils key={i} className="w-3.5 h-3.5 text-orange-500/70" />
                                        ))}
                                    </div>
                                )}
                                {Math.floor((day.getTime() - new Date(plan.startDate).setHours(0, 0, 0, 0)) / (1000 * 60 * 60 * 24)) % plan.litterInterval === 0 && (
                                    <div className="flex items-center gap-1 text-xs text-muted-foreground/70" title={dict.litter}>
                                        <Trash2 className="w-3.5 h-3.5 text-blue-500/70" />
                                    </div>
                                )}
                            </div>
                        </div>
                    )
                })}
            </div>

            {/* Cancellation Dialog */}
            <Dialog open={isCancelDialogOpen} onOpenChange={setIsCancelDialogOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>{dict.cancelTitle}</DialogTitle>
                        <DialogDescription>
                            {dict.cancelConfirm}
                        </DialogDescription>
                    </DialogHeader>

                    {plan.webhookUrl && (
                        <div className="grid gap-2 py-4">
                            <Label htmlFor="reason">{dict.cancelMessageLabel}</Label>
                            <Input
                                id="reason"
                                value={cancelReason}
                                onChange={(e) => setCancelReason(e.target.value)}
                                placeholder={dict.cancelMessagePlaceholder}
                                autoFocus
                            />
                        </div>
                    )}

                    <DialogFooter>
                        <Button variant="outline" onClick={() => setIsCancelDialogOpen(false)} disabled={isSubmitting}>
                            {dict.cancel}
                        </Button>
                        <Button variant="destructive" onClick={handleConfirmCancel} disabled={isSubmitting}>
                            {isSubmitting ? dict.saving : dict.cancelSubmit}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Completion Dialog */}
            <Dialog open={isCompleteDialogOpen} onOpenChange={setIsCompleteDialogOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>{dict.completeTitle}</DialogTitle>
                        <DialogDescription>
                            {dict.completeDesc}
                        </DialogDescription>
                    </DialogHeader>

                    <div className="grid gap-4 py-4">
                        <div className="grid gap-2">
                            <Label htmlFor="message">{dict.completeMessage}</Label>
                            <Textarea
                                id="message"
                                value={completionMessage}
                                onChange={(e) => setCompletionMessage(e.target.value)}
                                placeholder={dict.completeMessagePlaceholder}
                            />
                        </div>

                        <div className="grid gap-2">
                            <Label htmlFor="photo">{dict.completePhoto}</Label>
                            <div className="flex items-center gap-4">
                                <Button variant="outline" size="icon" className="w-12 h-12" onClick={() => document.getElementById('photo-upload')?.click()}>
                                    <Camera className="w-6 h-6" />
                                </Button>
                                <Input
                                    id="photo-upload"
                                    type="file"
                                    accept="image/*"
                                    capture="environment"
                                    className="hidden"
                                    onChange={handleImageChange}
                                />
                                {imagePreview && (
                                    <div className="relative w-20 h-20 rounded-md overflow-hidden border">
                                        <img src={imagePreview} alt="Preview" className="w-full h-full object-cover" />
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            className="absolute top-0 right-0 h-5 w-5 bg-background/50 hover:bg-background"
                                            onClick={() => {
                                                setCompletionImage(null)
                                                setImagePreview(null)
                                            }}
                                        >
                                            <X className="w-3 h-3" />
                                        </Button>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>

                    <DialogFooter>
                        <Button variant="outline" onClick={() => setIsCompleteDialogOpen(false)} disabled={isSubmitting}>
                            {dict.cancel}
                        </Button>
                        <Button onClick={handleConfirmComplete} disabled={isSubmitting}>
                            {isSubmitting ? dict.completing : dict.completeSubmit}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    )
}
