"use client";

import * as React from "react";
import { SearchIcon } from "lucide-react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { Button } from "@/components/ui/button";
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxList,
} from "@/components/ui/combobox";
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, InputGroupText } from "@/components/ui/input-group";
import { Label } from "@/components/ui/label";
import { NativeSelect, NativeSelectOptGroup, NativeSelectOption } from "@/components/ui/native-select";
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { branches, products } from "@/lib/mock-data";

/** The repo's Input is the login-page build (label, error, 52 px tall). These classes bring it to the dense 32 px control height. */

const CATEGORIES = [...new Set(products.map((p) => p.category))];
const PRODUCT_NAMES = products.filter((p) => p.type === "Product").map((p) => `${p.name} ${p.strength}`);

export function InputStates() {
  return (
    <Section id="input" title="Input" description="Text entry in each state. Focus and hover are live; try the first field.">
      <div className="grid gap-4 md:grid-cols-2">
        <Example title="States">
          <FieldGroup className="gap-4">
            <Field>
              <FieldLabel htmlFor="in-default">Default</FieldLabel>
              <Input id="in-default" placeholder="Product name" />
            </Field>
            <Field>
              <FieldLabel htmlFor="in-focus">Focus (forced)</FieldLabel>
              <Input id="in-focus" className="border-ring ring-3 ring-ring/50" defaultValue="Amoxil 500 mg" readOnly />
              <FieldDescription>Real focus is a 3 px teal ring at 50%. Click any field to see it.</FieldDescription>
            </Field>
            <Field>
              <FieldLabel htmlFor="in-disabled">Disabled</FieldLabel>
              <Input id="in-disabled" defaultValue="RCP-005200" disabled />
            </Field>
            <Field data-invalid="true">
              <FieldLabel htmlFor="in-error">Error</FieldLabel>
              <Input id="in-error" defaultValue="61611" aria-invalid aria-describedby="in-error-msg" />
              <FieldError id="in-error-msg">Barcode must be 8 to 14 digits.</FieldError>
            </Field>
          </FieldGroup>
        </Example>
              </div>
    </Section>
  );
}

export function InputGroups() {
  return (
    <Section id="input-group" title="Input group" description="Prefix, suffix, icon and button addons live inside one bordered control.">
      <Example title="Addons">
        <div className="grid gap-4 md:grid-cols-2">
          {/* InputGroupInput wraps the custom Input, so py/ring/text size are reset here. */}
          <InputGroup>
            <InputGroupAddon>
              <InputGroupText>KES</InputGroupText>
            </InputGroupAddon>
            <InputGroupInput className="py-0 text-sm tabular-nums focus:ring-0" placeholder="0.00" inputMode="decimal" aria-label="Amount in KES" />
          </InputGroup>
          <InputGroup>
            <InputGroupAddon>
              <SearchIcon />
            </InputGroupAddon>
            <InputGroupInput className="py-0 text-sm focus:ring-0" placeholder="Search products or scan barcode" aria-label="Search" />
          </InputGroup>
          <InputGroup>
            <InputGroupInput className="py-0 text-sm tabular-nums focus:ring-0" defaultValue="24" aria-label="Quantity" />
            <InputGroupAddon align="inline-end">
              <InputGroupText>units</InputGroupText>
            </InputGroupAddon>
          </InputGroup>
          <InputGroup>
            <InputGroupInput className="py-0 text-sm focus:ring-0" placeholder="Discount code" aria-label="Discount code" />
            <InputGroupAddon align="inline-end">
              <InputGroupButton variant="secondary">Apply</InputGroupButton>
            </InputGroupAddon>
          </InputGroup>
          <InputGroup aria-invalid="true" className="has-[[data-slot=input-group-control]]:border-destructive">
            <InputGroupAddon>
              <InputGroupText>KES</InputGroupText>
            </InputGroupAddon>
            <InputGroupInput className="py-0 text-sm tabular-nums focus:ring-0" defaultValue="-50" aria-invalid="true" aria-label="Price" />
          </InputGroup>
          <InputGroup className="opacity-50">
            <InputGroupAddon>
              <InputGroupText>KES</InputGroupText>
            </InputGroupAddon>
            <InputGroupInput className="py-0 text-sm focus:ring-0" defaultValue="2,400" disabled aria-label="Locked price" />
          </InputGroup>
        </div>
      </Example>
    </Section>
  );
}

export function TextareaAndField() {
  return (
    <Section id="textarea-field" title="Textarea, label and field" description="Field arranges label, control, helper text and error. FieldGroup spaces several fields; FieldSet and FieldLegend group related ones.">
      <div className="grid gap-4 md:grid-cols-2">
        <Example title="Textarea">
          <FieldGroup className="gap-4">
            <Field>
              <FieldLabel htmlFor="ta-default">Notes</FieldLabel>
              <Textarea id="ta-default" placeholder="Dosage instructions, allergies" />
              <FieldDescription>Printed on the receipt.</FieldDescription>
            </Field>
            <Field data-invalid="true">
              <FieldLabel htmlFor="ta-error">Reason for refund</FieldLabel>
              <Textarea id="ta-error" aria-invalid="true" />
              <FieldError>A reason is required.</FieldError>
            </Field>
            <Field>
              <FieldLabel htmlFor="ta-disabled">Disabled</FieldLabel>
              <Textarea id="ta-disabled" disabled defaultValue="Locked after dispensing." />
            </Field>
          </FieldGroup>
        </Example>
        <Example title="Label, orientation, FieldError list">
          <FieldGroup className="gap-4">
            <Field>
              <Label htmlFor="lb-plain">Plain Label</Label>
              <Input id="lb-plain" />
            </Field>
            <Field orientation="horizontal">
              <FieldLabel htmlFor="lb-h" className="w-28 shrink-0">
                Horizontal
              </FieldLabel>
              <Input id="lb-h" placeholder="Label beside control" />
            </Field>
            <Field data-invalid="true">
              <FieldLabel htmlFor="lb-multi">Password</FieldLabel>
              <Input id="lb-multi" type="password" aria-invalid />
              <FieldError errors={[{ message: "At least 8 characters" }, { message: "One number" }]} />
            </Field>
          </FieldGroup>
        </Example>
      </div>
    </Section>
  );
}

export function SelectsAndCombobox() {
  const [product, setProduct] = React.useState<string | null>(null);
  return (
    <Section id="select" title="Select and combobox" description="Select picks from a short fixed list. Combobox adds type-ahead for long lists such as the product catalogue. Native select is the fallback for mobile and long forms.">
      <div className="grid gap-4 md:grid-cols-2">
        <Example title="Select">
          <FieldGroup className="gap-4">
            <Field>
              <FieldLabel>Category</FieldLabel>
              <Select defaultValue="Analgesics">
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="Choose category" />
                </SelectTrigger>
                <SelectContent>
                  <SelectGroup>
                    <SelectLabel>Categories</SelectLabel>
                    {CATEGORIES.map((c) => (
                      <SelectItem key={c} value={c}>
                        {c}
                      </SelectItem>
                    ))}
                  </SelectGroup>
                </SelectContent>
              </Select>
            </Field>
            <Field>
              <FieldLabel>Placeholder</FieldLabel>
              <Select>
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="Select a branch" />
                </SelectTrigger>
                <SelectContent>
                  {branches.map((b) => (
                    <SelectItem key={b.id} value={String(b.id)}>
                      {b.name}, {b.town}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </Field>
            <Field data-invalid="true">
              <FieldLabel>Error</FieldLabel>
              <Select>
                <SelectTrigger className="w-full" aria-invalid="true">
                  <SelectValue placeholder="Select a supplier" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">Dawa Distributors Ltd</SelectItem>
                </SelectContent>
              </Select>
              <FieldError>Choose a supplier.</FieldError>
            </Field>
            <Field>
              <FieldLabel>Disabled</FieldLabel>
              <Select disabled defaultValue="Antibiotics">
                <SelectTrigger className="w-full">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Antibiotics">Antibiotics</SelectItem>
                </SelectContent>
              </Select>
            </Field>
          </FieldGroup>
        </Example>
        <div className="space-y-4">
          <Example title="Combobox, product search" description="Type to filter, 40 products">
            <Field>
              <FieldLabel htmlFor="cb-product">Product</FieldLabel>
              <Combobox items={PRODUCT_NAMES} value={product} onValueChange={setProduct}>
                <ComboboxInput id="cb-product" placeholder="Search products" showClear />
                <ComboboxContent>
                  <ComboboxEmpty>No product found.</ComboboxEmpty>
                  <ComboboxList>
                    {(item: string) => (
                      <ComboboxItem key={item} value={item}>
                        {item}
                      </ComboboxItem>
                    )}
                  </ComboboxList>
                </ComboboxContent>
              </Combobox>
              <FieldDescription>{product ? `Selected: ${product}` : "Nothing selected."}</FieldDescription>
            </Field>
          </Example>
          <Example title="Native select">
            <FieldGroup className="gap-4">
              <Field>
                <FieldLabel htmlFor="ns-1">Unit of measure</FieldLabel>
                <NativeSelect id="ns-1" className="w-full" defaultValue="tablet">
                  <NativeSelectOption value="tablet">Tablet</NativeSelectOption>
                  <NativeSelectOption value="capsule">Capsule</NativeSelectOption>
                  <NativeSelectOptGroup label="Liquids">
                    <NativeSelectOption value="syrup">Syrup</NativeSelectOption>
                    <NativeSelectOption value="inhaler">Inhaler</NativeSelectOption>
                  </NativeSelectOptGroup>
                </NativeSelect>
              </Field>
              <Field>
                <FieldLabel htmlFor="ns-2">Small, disabled</FieldLabel>
                <NativeSelect id="ns-2" size="sm" disabled>
                  <NativeSelectOption>Westlands Main</NativeSelectOption>
                </NativeSelect>
              </Field>
            </FieldGroup>
          </Example>
        </div>
      </div>
      <Example title="Button beside field" description="A quiet check that Button and controls share height">
        <div className="flex max-w-md items-center gap-2">
          <Input placeholder="Barcode" aria-label="Barcode" />
          <Button variant="outline">Look up</Button>
        </div>
      </Example>
    </Section>
  );
}
