"use client";

import * as React from "react";
import { BanknoteIcon, CreditCardIcon, SmartphoneIcon, UserRoundIcon } from "lucide-react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { Checkbox } from "@/components/ui/checkbox";
import { Field, FieldContent, FieldDescription, FieldGroup, FieldLabel, FieldLegend, FieldSet, FieldTitle } from "@/components/ui/field";
import { InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot } from "@/components/ui/input-otp";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Slider } from "@/components/ui/slider";
import { Switch } from "@/components/ui/switch";
import { formatKES } from "@/lib/mock-data";

const PAYMENTS = [
  { value: "cash", label: "Cash", hint: "Counted at the till", icon: BanknoteIcon },
  { value: "mpesa", label: "M-Pesa", hint: "STK push to the customer", icon: SmartphoneIcon },
  { value: "card", label: "Card", hint: "Visa, Mastercard", icon: CreditCardIcon },
  { value: "credit", label: "Credit", hint: "Put on the customer's account", icon: UserRoundIcon },
] as const;

export function CheckboxSection() {
  const [items, setItems] = React.useState({ low: true, expiring: false, rx: false });
  const all = Object.values(items).every(Boolean);
  const some = Object.values(items).some(Boolean);
  const [terms, setTerms] = React.useState(false);
  return (
    <Section id="checkbox" title="Checkbox" description="Independent yes/no choices. Indeterminate shows a mixed selection in a group.">
      <div className="grid gap-4 md:grid-cols-2">
        <Example title="States">
          <FieldGroup className="gap-3">
            {[
              { id: "cb-un", label: "Unchecked", props: {} },
              { id: "cb-ch", label: "Checked", props: { defaultChecked: true } },
              { id: "cb-in", label: "Indeterminate", props: { indeterminate: true } },
              { id: "cb-di", label: "Disabled", props: { disabled: true } },
              { id: "cb-dc", label: "Disabled, checked", props: { disabled: true, defaultChecked: true } },
              { id: "cb-er", label: "Invalid", props: { "aria-invalid": true as const } },
            ].map((c) => (
              <Field key={c.id} orientation="horizontal">
                <Checkbox id={c.id} {...c.props} />
                <FieldLabel htmlFor={c.id} className="font-normal">
                  {c.label}
                </FieldLabel>
              </Field>
            ))}
            <Field orientation="horizontal">
              <Checkbox id="cb-desc" checked={terms} onCheckedChange={(v) => setTerms(Boolean(v))} />
              <FieldContent>
                <FieldLabel htmlFor="cb-desc">Customer collected the medicine</FieldLabel>
                <FieldDescription>With description text beneath the label.</FieldDescription>
              </FieldContent>
            </Field>
          </FieldGroup>
        </Example>
        <Example title="Group with select-all">
          <FieldSet>
            <FieldLegend variant="label">Inventory alerts</FieldLegend>
            <Field orientation="horizontal">
              <Checkbox
                id="cb-all"
                checked={all}
                indeterminate={some && !all}
                onCheckedChange={(v) => setItems({ low: Boolean(v), expiring: Boolean(v), rx: Boolean(v) })}
              />
              <FieldLabel htmlFor="cb-all">Select all</FieldLabel>
            </Field>
            <div className="ml-6 flex flex-col gap-3">
              {(
                [
                  ["low", "Low stock"],
                  ["expiring", "Expiring within 90 days"],
                  ["rx", "Prescription items only"],
                ] as const
              ).map(([k, label]) => (
                <Field key={k} orientation="horizontal">
                  <Checkbox id={`cb-${k}`} checked={items[k]} onCheckedChange={(v) => setItems((s) => ({ ...s, [k]: Boolean(v) }))} />
                  <FieldLabel htmlFor={`cb-${k}`} className="font-normal">
                    {label}
                  </FieldLabel>
                </Field>
              ))}
            </div>
          </FieldSet>
        </Example>
      </div>
    </Section>
  );
}

export function RadioSection() {
  const [pay, setPay] = React.useState("mpesa");
  return (
    <Section id="radio" title="Radio group" description="One choice from a short list. The card form is for payment method at the till.">
      <div className="grid gap-4 md:grid-cols-2">
        <Example title="Payment method, cards" description="Selected: tinted border">
          <RadioGroup value={pay} onValueChange={setPay} className="grid-cols-2">
            {PAYMENTS.map((p) => (
              <FieldLabel key={p.value} htmlFor={`pay-${p.value}`}>
                <Field orientation="horizontal">
                  <FieldContent>
                    <FieldTitle>
                      <p.icon className="size-4" />
                      {p.label}
                    </FieldTitle>
                    <FieldDescription>{p.hint}</FieldDescription>
                  </FieldContent>
                  <RadioGroupItem id={`pay-${p.value}`} value={p.value} />
                </Field>
              </FieldLabel>
            ))}
          </RadioGroup>
        </Example>
        <Example title="Simple and states">
          <div className="grid grid-cols-2 gap-4">
            <RadioGroup defaultValue="product" className="gap-3">
              {["Product", "Service"].map((t) => (
                <div key={t} className="flex items-center gap-2">
                  <RadioGroupItem id={`rg-${t}`} value={t.toLowerCase()} />
                  <Label htmlFor={`rg-${t}`} className="font-normal">
                    {t}
                  </Label>
                </div>
              ))}
            </RadioGroup>
            <RadioGroup defaultValue="b" className="gap-3">
              <div className="flex items-center gap-2">
                <RadioGroupItem id="rg-d1" value="a" disabled />
                <Label htmlFor="rg-d1" className="font-normal opacity-50">
                  Disabled
                </Label>
              </div>
              <div className="flex items-center gap-2">
                <RadioGroupItem id="rg-d2" value="b" disabled />
                <Label htmlFor="rg-d2" className="font-normal opacity-50">
                  Disabled, selected
                </Label>
              </div>
              <div className="flex items-center gap-2">
                <RadioGroupItem id="rg-d3" value="c" aria-invalid />
                <Label htmlFor="rg-d3" className="font-normal">
                  Invalid
                </Label>
              </div>
            </RadioGroup>
          </div>
        </Example>
      </div>
    </Section>
  );
}

export function SwitchSliderOtp() {
  const [price, setPrice] = React.useState([450]);
  const [range, setRange] = React.useState([100, 600]);
  const [otp, setOtp] = React.useState("");
  return (
    <Section id="switch-slider-otp" title="Switch, slider and input OTP">
      <div className="grid gap-4 md:grid-cols-3">
        <Example title="Switch">
          <FieldGroup className="gap-3">
            <Field orientation="horizontal">
              <Switch id="sw-1" defaultChecked />
              <FieldLabel htmlFor="sw-1">Requires prescription</FieldLabel>
            </Field>
            <Field orientation="horizontal">
              <Switch id="sw-2" />
              <FieldLabel htmlFor="sw-2">Print receipt</FieldLabel>
            </Field>
            <Field orientation="horizontal">
              <Switch id="sw-3" size="sm" defaultChecked />
              <FieldLabel htmlFor="sw-3">Small</FieldLabel>
            </Field>
            <Field orientation="horizontal">
              <Switch id="sw-4" disabled />
              <FieldLabel htmlFor="sw-4">Disabled</FieldLabel>
            </Field>
            <Field orientation="horizontal">
              <Switch id="sw-5" disabled defaultChecked />
              <FieldLabel htmlFor="sw-5">Disabled, on</FieldLabel>
            </Field>
          </FieldGroup>
        </Example>
        <Example title="Slider">
          <div className="space-y-6">
            <div className="space-y-3">
              <div className="flex justify-between text-sm">
                <Label>Max price</Label>
                <span className="tabular-nums text-muted-foreground">{formatKES(price[0])}</span>
              </div>
              <Slider value={price} onValueChange={(v) => setPrice(Array.isArray(v) ? [...v] : [v])} min={0} max={2400} step={50} aria-label="Max price" />
            </div>
            <div className="space-y-3">
              <div className="flex justify-between text-sm">
                <Label>Price range</Label>
                <span className="tabular-nums text-muted-foreground">
                  {formatKES(range[0])} to {formatKES(range[1])}
                </span>
              </div>
              <Slider value={range} onValueChange={(v) => setRange(Array.isArray(v) ? [...v] : [v])} min={0} max={2400} step={50} aria-label="Price range" />
            </div>
            <Slider defaultValue={[30]} disabled aria-label="Disabled" />
          </div>
        </Example>
        <Example title="Input OTP" description="Confirm M-Pesa code">
          <div className="space-y-4">
            <InputOTP maxLength={6} value={otp} onChange={setOtp} aria-label="Verification code">
              <InputOTPGroup>
                <InputOTPSlot index={0} />
                <InputOTPSlot index={1} />
                <InputOTPSlot index={2} />
              </InputOTPGroup>
              <InputOTPSeparator />
              <InputOTPGroup>
                <InputOTPSlot index={3} />
                <InputOTPSlot index={4} />
                <InputOTPSlot index={5} />
              </InputOTPGroup>
            </InputOTP>
            <p className="text-xs text-muted-foreground">{otp.length === 6 ? "Code entered." : `${6 - otp.length} digits left.`}</p>
            <InputOTP maxLength={4} disabled aria-label="Disabled code">
              <InputOTPGroup>
                {[0, 1, 2, 3].map((i) => (
                  <InputOTPSlot key={i} index={i} />
                ))}
              </InputOTPGroup>
            </InputOTP>
            <InputOTP maxLength={4} aria-label="Invalid code" aria-invalid value="12" onChange={() => {}}>
              <InputOTPGroup>
                {[0, 1, 2, 3].map((i) => (
                  <InputOTPSlot key={i} index={i} aria-invalid />
                ))}
              </InputOTPGroup>
            </InputOTP>
          </div>
        </Example>
      </div>
    </Section>
  );
}
