import * as React from "react";
import { CalendarDays, ChevronLeft, ChevronRight } from "lucide-react";
import { Button } from "./button";
import { Popover, PopoverContent, PopoverTrigger } from "./popover";
import { cn } from "@/lib/utils";

export type DateRangeValue = { from: string; to: string };

type Props = {
    value: DateRangeValue;
    onChange: (value: DateRangeValue) => void;
    className?: string;
};

const formatDate = (value: string) =>
    value
        ? new Intl.DateTimeFormat("id-ID", {
              day: "2-digit",
              month: "short",
              year: "numeric",
          }).format(new Date(`${value}T00:00:00`))
        : "Pilih tanggal";

export function DateRangePicker({ value, onChange, className }: Props) {
    const [open, setOpen] = React.useState(false);
    const [month, setMonth] = React.useState(() => {
        const source = value.from || new Date().toISOString().slice(0, 10);
        return new Date(`${source.slice(0, 7)}-01T00:00:00`);
    });

    const monthLabel = new Intl.DateTimeFormat("id-ID", {
        month: "long",
        year: "numeric",
    }).format(month);

    const shiftMonth = (delta: number) => {
        setMonth((current) => {
            const next = new Date(current);
            next.setMonth(next.getMonth() + delta);
            return next;
        });
    };

    return (
        <Popover open={open} onOpenChange={setOpen}>
            <PopoverTrigger asChild>
                <Button
                    type="button"
                    variant="outline"
                    className={cn(
                        "w-full justify-start font-normal",
                        className,
                    )}
                >
                    <CalendarDays className="mr-2 h-4 w-4" />
                    {value.from && value.to
                        ? `${formatDate(value.from)} – ${formatDate(value.to)}`
                        : value.from
                          ? formatDate(value.from)
                          : "Pilih periode"}
                </Button>
            </PopoverTrigger>
            <PopoverContent className="w-85 p-3" align="start">
                <div className="mb-3 flex items-center justify-between">
                    <Button
                        type="button"
                        variant="ghost"
                        size="icon-sm"
                        onClick={() => shiftMonth(-1)}
                    >
                        <ChevronLeft />
                    </Button>
                    <div className="text-sm font-semibold capitalize">
                        {monthLabel}
                    </div>
                    <Button
                        type="button"
                        variant="ghost"
                        size="icon-sm"
                        onClick={() => shiftMonth(1)}
                    >
                        <ChevronRight />
                    </Button>
                </div>
                <div className="grid gap-3">
                    <div>
                        <div className="mb-1.5 text-xs font-medium text-muted-foreground">
                            Tanggal mulai
                        </div>
                        <input
                            type="date"
                            value={value.from}
                            onChange={(e) => {
                                const from = e.target.value;
                                onChange({
                                    from,
                                    to:
                                        value.to && value.to < from
                                            ? from
                                            : value.to,
                                });
                                if (from)
                                    setMonth(
                                        new Date(
                                            `${from.slice(0, 7)}-01T00:00:00`,
                                        ),
                                    );
                            }}
                            className="border-input bg-background h-9 w-full rounded-md border px-3 text-sm outline-none focus:ring-2 focus:ring-ring/30"
                        />
                    </div>
                    <div>
                        <div className="mb-1.5 text-xs font-medium text-muted-foreground">
                            Tanggal selesai
                        </div>
                        <input
                            type="date"
                            min={value.from || undefined}
                            value={value.to}
                            onChange={(e) =>
                                onChange({ ...value, to: e.target.value })
                            }
                            className="border-input bg-background h-9 w-full rounded-md border px-3 text-sm outline-none focus:ring-2 focus:ring-ring/30"
                        />
                    </div>
                </div>
                <div className="mt-3 rounded-md bg-muted/50 p-2 text-xs text-muted-foreground">
                    Pilih tanggal mulai dan selesai. Semua tanggal di dalam
                    rentang akan dibuat sebagai target harian.
                </div>
            </PopoverContent>
        </Popover>
    );
}
