"use client";

import { Building2, CalendarDays, Factory, Grid3x3, Info, PackagePlus, Shirt, X } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { FieldGroup } from "@/components/ui/field";
import { Separator } from "@/components/ui/separator";
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Spinner } from "@/components/ui/spinner";
import { ComboboxField, FormErrorAlert, SelectField, SwitchField, TagsField, TextField } from "@/components/app/form-fields";
import { QuantityMatrix } from "@/components/app/quantity-matrix";
import { formatNumber } from "../lib/format";
import { closeQuickOrder, useQuickOrderForm, useQuickOrderStore } from "./useQuickOrderForm";

/**
 * "Put in a running order" (design S4). Mounted once by the app shell; open it from anywhere with
 * openQuickOrder(from). The form only mounts while the sheet is open, so its lookups load on demand.
 */
export function QuickOrderSheet() {
  const open = useQuickOrderStore((state) => state.open);

  return <Sheet open={open} onOpenChange={(next) => { if (!next) closeQuickOrder(); }}>
    {open && <QuickOrderForm />}
  </Sheet>;
}

function Step({ icon: Icon, title, hint, children }) {
  return <section className="grid gap-4" aria-label={title}>
    <div className="flex items-start gap-2.5">
      <span className="grid size-7 shrink-0 place-items-center rounded-full bg-muted text-muted-foreground"><Icon className="size-3.5" aria-hidden="true" /></span>
      <div className="grid gap-0.5">
        <h3 className="text-sm font-semibold leading-7">{title}</h3>
        {hint && <p className="text-xs text-muted-foreground">{hint}</p>}
      </div>
    </div>
    <div className="grid gap-4 sm:pl-9">{children}</div>
  </section>;
}

function QuickOrderForm() {
  const quick = useQuickOrderForm({ onDone: closeQuickOrder });
  const { form, submit, guard, lookups, rows, columns, perSize, split } = quick;
  const isSubmitting = form.formState.isSubmitting;
  const cellsError = form.formState.errors.cells?.message;
  const cells = rows.length * columns.length;

  const requestClose = guard.guardOpenChange((next) => { if (!next) closeQuickOrder(); });

  return <SheetContent side="right" showCloseButton={false} className="w-full gap-0 overflow-y-auto sm:max-w-xl" onInteractOutside={(event) => { event.preventDefault(); requestClose(false); }} onEscapeKeyDown={(event) => { event.preventDefault(); requestClose(false); }}>
    <form onSubmit={submit} noValidate className="flex min-h-full flex-col">
      <SheetHeader className="relative border-b pr-12">
        <SheetTitle className="flex items-center gap-2 text-lg"><PackagePlus className="size-5 text-muted-foreground" aria-hidden="true" /> Put in a running order</SheetTitle>
        <SheetDescription>For an order the buyer has already confirmed. You can add costing and history later.</SheetDescription>
        <Button type="button" variant="ghost" size="icon-sm" className="absolute right-3 top-3" aria-label="Close" onClick={() => requestClose(false)}><X /></Button>
      </SheetHeader>

      <div className="grid flex-1 content-start gap-6 p-4 sm:p-6">
        <FormErrorAlert form={form} />

        <Step icon={Building2} title="Buyer" hint={quick.canAddBuyer ? "Type a new name to add the buyer." : "Ask an admin to add a buyer that is not in the list."}>
          <FieldGroup className="gap-4">
            <ComboboxField control={form.control} name="buyer_id" label="Buyer" options={quick.buyerOptions}
              placeholder={lookups.isLoading ? "Loading buyers…" : "Choose or add a buyer"} searchPlaceholder="Search buyers…" emptyText="No buyer matches."
              create={quick.buyerCreate} loading={lookups.isLoading} />
            <div className="grid gap-4 sm:grid-cols-2">
              <TextField control={form.control} name="buyer_po_no" label="Buyer PO number" placeholder="e.g. 4500123456" description="Exactly as printed on the buyer's PO." />
              <TextField control={form.control} name="order_date" label="Order date" type="date" />
            </div>
          </FieldGroup>
        </Step>

        <Separator />

        <Step icon={Shirt} title="Style">
          <FieldGroup className="gap-4">
            <div className="grid gap-4 sm:grid-cols-2">
              <TextField control={form.control} name="style_ref" label="Style ref" placeholder="e.g. NV-2231" description="Buyer's style number." />
              <ComboboxField control={form.control} name="product_category_id" label="Product category" options={quick.categoryOptions} allowEmpty emptyLabel="Not set"
                placeholder="Optional" searchPlaceholder="Search categories…" emptyText="No category matches." create={quick.categoryCreate} />
            </div>
            <TextField control={form.control} name="style_description" label="Description" placeholder="e.g. Men's crew neck tee" description="Optional." />
          </FieldGroup>
        </Step>

        <Separator />

        <Step icon={Grid3x3} title="Colours and sizes" hint="Each colour × size becomes a line on the PO.">
          <FieldGroup className="gap-4">
            <div className="grid gap-4 sm:grid-cols-2">
              <TagsField control={form.control} name="colours" label="Colours" placeholder="Black, Navy" />
              <TagsField control={form.control} name="sizes" label="Sizes" placeholder="S, M, L, XL" />
            </div>
            <SwitchField control={form.control} name="per_size" label="Enter quantity per colour and size" description="Leave off to split one total evenly." />
            {!perSize && <div className="grid gap-2">
              <TextField control={form.control} name="total_quantity" label="Total quantity (pcs)" type="number" placeholder="e.g. 12000" inputProps={{ min: 1, step: 1, inputMode: "numeric" }} />
              {split && cells > 1 && <p className="flex items-start gap-1.5 text-xs text-muted-foreground" aria-live="polite">
                <Info className="mt-0.5 size-3.5 shrink-0" aria-hidden="true" />
                Split evenly: {formatNumber(split.each)} pcs in each of the {cells} colour × size lines{split.first !== split.each ? ` (${formatNumber(split.first)} on the first)` : ""}. Adjust later on the PO.
              </p>}
            </div>}
            {perSize && (rows.length && columns.length
              ? <div className="grid gap-2">
                <QuantityMatrix control={form.control} rows={rows} columns={columns} caption="Order quantity by colour and size" />
                {cellsError && <p className="text-sm text-destructive" role="alert">{cellsError}</p>}
              </div>
              : <p className="rounded-lg border border-dashed bg-muted/30 p-4 text-center text-sm text-muted-foreground">Add colours and sizes above to fill in the grid.</p>)}
          </FieldGroup>
        </Step>

        <Separator />

        <Step icon={CalendarDays} title="Price and dates">
          <FieldGroup className="gap-4">
            <div className="grid gap-4 sm:grid-cols-2">
              <TextField control={form.control} name="unit_price" label="Unit price" type="number" placeholder="Optional" inputProps={{ min: 0, step: "0.0001", inputMode: "decimal" }} description="Per piece, as on the buyer PO." />
              <SelectField control={form.control} name="currency_id" label="Currency" options={quick.currencyOptions} placeholder="Choose currency" description="Follows the buyer's currency." />
            </div>
            <TextField control={form.control} name="ship_date" label="Ship date (ex-factory)" type="date" description="The day goods leave the factory. Dates in the plan count back from it." />
          </FieldGroup>
        </Step>

        <Separator />

        <Step icon={Factory} title="Factory (optional)" hint="Adding the factory now splits the whole order to it. You can change the split later.">
          <FieldGroup className="gap-4">
            <ComboboxField control={form.control} name="factory_id" label="Factory" options={quick.factoryOptions} allowEmpty emptyLabel="Decide later"
              placeholder={lookups.isLoading ? "Loading factories…" : "Decide later"} searchPlaceholder="Search factories…" emptyText="No factory matches."
              create={quick.factoryCreate} loading={lookups.isLoading}
              description={quick.canAddFactory ? "Type a new name to add the factory. A new factory starts as pending approval." : "Ask an admin to add a factory that is not in the list."} />
          </FieldGroup>
        </Step>

        <Alert className="bg-muted/30">
          <Info />
          <AlertDescription>The order is recorded as a running order (confirmed before it was tracked here), so no quote is needed. Its history starts today.</AlertDescription>
        </Alert>
      </div>

      <SheetFooter className="sticky bottom-0 z-10 flex-col-reverse gap-2 border-t bg-background sm:flex-row sm:justify-end">
        <Button type="button" variant="outline" onClick={() => requestClose(false)} disabled={isSubmitting}>Cancel</Button>
        <Button type="submit" disabled={isSubmitting}>{isSubmitting ? <Spinner /> : <PackagePlus />} {isSubmitting ? "Putting it on the board…" : "Put order on the board"}</Button>
      </SheetFooter>
    </form>
  </SheetContent>;
}
