import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/components/ui/popover"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Clock, Check } from "lucide-react"
import { cn } from "@/lib/utils"
import { Field, FieldDescription, FieldLabel } from "../ui/field"

interface TimePickerProps {
    value?: string | null // stored as HH:mm (24h)
    onChange?: (time: string) => void
    className?: string
    disabled?: boolean,
    error?: string,
    label: string,
    requred?: boolean
}

export default function TimePicker({
    value,
    onChange,
    className,
    disabled,
    error,
    label,
    requred
}: TimePickerProps) {

    const [open, setOpen] = useState(false)
    const [hour, setHour] = useState("01")
    const [minute, setMinute] = useState("00")
    const [period, setPeriod] = useState<"AM" | "PM">("AM")

    // Convert 24h → 12h when loading value
    useEffect(() => {
        if (!value) return

        const [h, m] = value.split(":").map(Number)

        const isPM = h >= 12
        const hour12 = h % 12 === 0 ? 12 : h % 12

        setHour(hour12.toString().padStart(2, "0"))
        setMinute(m.toString().padStart(2, "0"))
        setPeriod(isPM ? "PM" : "AM")
    }, [value])

    // Convert 12h → 24h when saving
    const apply = () => {
        let h = Number(hour)

        if (period === "PM" && h !== 12) h += 12
        if (period === "AM" && h === 12) h = 0

        const formatted = `${h.toString().padStart(2, "0")}:${minute}`
        onChange?.(formatted)
        setOpen(false)
    }

    const hours = Array.from({ length: 12 }, (_, i) =>
        (i + 1).toString().padStart(2, "0")
    )

    const minutes = Array.from({ length: 12 }, (_, i) =>
        (i * 5).toString().padStart(2, "0") // 5 min steps (clean UX)
    )

    return (<Field className={cn('gap-1 flex-1', className)}>
        <FieldLabel className=''>{label} {requred && <span className="text-destructive">*</span>}</FieldLabel>

        <Popover open={open} onOpenChange={setOpen}>
            <PopoverTrigger asChild>
                <Button
                    variant="outline"
                    disabled={disabled}
                    className={cn("w-full justify-between", className)}
                >
                    {value
                        ? `${hour}:${minute} ${period}`
                        : "Select time"}
                    <Clock className="ml-2 h-4 w-4" />
                </Button>
            </PopoverTrigger>

            <PopoverContent className="w-80 p-4 space-y-4">

                <div className="flex gap-3">

                    {/* Hour */}
                    <div className="flex-1">
                        <p className="text-xs text-muted-foreground mb-2">Hour</p>
                        <ScrollArea className="h-40 border rounded-md">
                            {hours.map((h) => (
                                <div
                                    key={h}
                                    onClick={() => setHour(h)}
                                    className={cn(
                                        "px-3 py-2 text-sm cursor-pointer flex justify-between hover:bg-muted",
                                        hour === h && "bg-muted font-medium"
                                    )}
                                >
                                    {h}
                                    {hour === h && <Check className="h-4 w-4" />}
                                </div>
                            ))}
                        </ScrollArea>
                    </div>

                    {/* Minute */}
                    <div className="flex-1">
                        <p className="text-xs text-muted-foreground mb-2">Minute</p>
                        <ScrollArea className="h-40 border rounded-md">
                            {minutes.map((m) => (
                                <div
                                    key={m}
                                    onClick={() => setMinute(m)}
                                    className={cn(
                                        "px-3 py-2 text-sm cursor-pointer flex justify-between hover:bg-muted",
                                        minute === m && "bg-muted font-medium"
                                    )}
                                >
                                    {m}
                                    {minute === m && <Check className="h-4 w-4" />}
                                </div>
                            ))}
                        </ScrollArea>
                    </div>

                    {/* AM / PM */}
                    <div className="flex flex-col justify-center gap-2">
                        {["AM", "PM"].map((p) => (
                            <Button
                                key={p}
                                variant={period === p ? "default" : "outline"}
                                size="sm"
                                onClick={() => setPeriod(p as "AM" | "PM")}
                            >
                                {p}
                            </Button>
                        ))}
                    </div>

                </div>

                <Button className="w-full" onClick={apply}>
                    Apply Time
                </Button>

            </PopoverContent>
        </Popover>
        {error && <FieldDescription className='text-red-600 text-sm'>{error}</FieldDescription>}

    </Field >
    )
}