"use client";

import * as React from "react";
import { CalendarIcon, PackageIcon, PillIcon, ScanBarcodeIcon, ShoppingCartIcon, UsersIcon } from "lucide-react";
import type { DateRange } from "react-day-picker";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut } from "@/components/ui/command";
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { formatDate } from "@/lib/mock-data";

/** Local-date to ISO without timezone shifting, so formatDate() output is stable. */
export const toIso = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;

const TODAY = new Date(2026, 9, 20);
const MONTH = new Date(2026, 9, 1);

export function DatePicker({ value, onChange, id, invalid }: { value?: Date; onChange: (d: Date | undefined) => void; id?: string; invalid?: boolean }) {
  const [open, setOpen] = React.useState(false);
  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger
        id={id}
        aria-invalid={invalid || undefined}
        render={<Button variant="outline" className="w-full justify-start font-normal aria-invalid:border-destructive" />}
      >
        <CalendarIcon data-icon="inline-start" />
        <span className={value ? "tabular-nums" : "text-muted-foreground"}>{value ? formatDate(toIso(value)) : "Pick a date"}</span>
      </PopoverTrigger>
      <PopoverContent align="start" className="w-auto p-0">
        <Calendar
          mode="single"
          selected={value}
          onSelect={(d) => {
            onChange(d);
            setOpen(false);
          }}
          defaultMonth={value ?? MONTH}
        />
      </PopoverContent>
    </Popover>
  );
}

export function CalendarSection() {
  const [day, setDay] = React.useState<Date | undefined>(TODAY);
  const [picked, setPicked] = React.useState<Date | undefined>();
  const [range, setRange] = React.useState<DateRange | undefined>({ from: new Date(2026, 9, 6), to: new Date(2026, 9, 20) });
  const [popRange, setPopRange] = React.useState<DateRange | undefined>();
  const [open, setOpen] = React.useState(false);
  return (
    <Section id="calendar" title="Calendar and dates" description="Inline calendar for scheduling, a popover date picker for forms, and a range picker for report periods.">
      <div className="grid gap-4 md:grid-cols-2">
        <Example title="Calendar, single" description={day ? formatDate(toIso(day)) : "No date"}>
          <Calendar mode="single" selected={day} onSelect={setDay} defaultMonth={MONTH} className="rounded-lg border border-border" />
        </Example>
        <div className="space-y-4">
          <Example title="Date picker (popover)" description="Expiry date field">
            <Field>
              <FieldLabel htmlFor="dp-expiry">Expiry date</FieldLabel>
              <DatePicker id="dp-expiry" value={picked} onChange={setPicked} />
              <FieldDescription>Opens a calendar in a popover and closes on selection.</FieldDescription>
            </Field>
          </Example>
          <Example title="Date range picker (popover)" description="Report period">
            <Field>
              <FieldLabel htmlFor="dr-trigger">Period</FieldLabel>
              <Popover open={open} onOpenChange={setOpen}>
                <PopoverTrigger id="dr-trigger" render={<Button variant="outline" className="w-full justify-start font-normal" />}>
                  <CalendarIcon data-icon="inline-start" />
                  <span className={popRange?.from ? "tabular-nums" : "text-muted-foreground"}>
                    {popRange?.from ? `${formatDate(toIso(popRange.from))}${popRange.to ? ` to ${formatDate(toIso(popRange.to))}` : ""}` : "Pick a range"}
                  </span>
                </PopoverTrigger>
                <PopoverContent align="start" className="w-auto p-0">
                  <Calendar mode="range" selected={popRange} onSelect={setPopRange} numberOfMonths={2} defaultMonth={MONTH} />
                </PopoverContent>
              </Popover>
            </Field>
          </Example>
        </div>
      </div>
      <Example title="Range calendar, inline" description={range?.from ? `${formatDate(toIso(range.from))} to ${range.to ? formatDate(toIso(range.to)) : "..."}` : "No range"}>
        <Calendar mode="range" selected={range} onSelect={setRange} numberOfMonths={2} defaultMonth={MONTH} className="rounded-lg border border-border" />
      </Example>
    </Section>
  );
}

export function CommandSection() {
  return (
    <Section id="command" title="Command" description="Searchable action list, the base of the command menu. Shown inline here; the overlays page has the dialog form.">
      <Example title="Command list">
        <Command className="max-w-md border border-border">
          <CommandInput placeholder="Search products, customers or actions" />
          <CommandList>
            <CommandEmpty>No results.</CommandEmpty>
            <CommandGroup heading="Actions">
              <CommandItem>
                <ShoppingCartIcon />
                New sale
                <CommandShortcut>F2</CommandShortcut>
              </CommandItem>
              <CommandItem>
                <ScanBarcodeIcon />
                Scan barcode
                <CommandShortcut>F3</CommandShortcut>
              </CommandItem>
              <CommandItem disabled>
                <PackageIcon />
                Receive stock
              </CommandItem>
            </CommandGroup>
            <CommandSeparator />
            <CommandGroup heading="Products">
              <CommandItem>
                <PillIcon />
                Panadol 500 mg
              </CommandItem>
              <CommandItem>
                <PillIcon />
                Augmentin 625 mg
              </CommandItem>
            </CommandGroup>
            <CommandGroup heading="Customers">
              <CommandItem>
                <UsersIcon />
                Mary Wambui
              </CommandItem>
            </CommandGroup>
          </CommandList>
        </Command>
      </Example>
    </Section>
  );
}
