import { useId, useState, type ComponentProps, type ReactNode } from 'react';
import { ChevronDown, LoaderCircle } from 'lucide-react';
import type { FormDataConvertible } from '@inertiajs/core';
import { useForm } from 'react-hook-form';
import { Button } from '@rutatiina/ui/components/ui/button';
import { Input } from '@rutatiina/ui/components/ui/input';
import { Label } from '@rutatiina/ui/components/ui/label';
import { useInertiaForm } from '@rutatiina/ui/hooks/use-inertia-form';
import { useTrans } from '@rutatiina/ui/lib/translations';
import { cn } from '@rutatiina/ui/lib/utils';

export type Field = {
  name: string;
  label: string;
  value?: string;
  options?: [string, string][];
  optional?: boolean;
  type?: 'text' | 'date' | 'file';
  /** A reference such as a receipt number: optional, made valid, and generated when left blank. */
  auto?: boolean;
  /** Sent when an optional field is left blank. */
  fallback?: string;
  hint?: string;
  /** Shown only while this holds for the values typed so far; a hidden field is sent blank. */
  show?: (values: Record<string, string>) => boolean;
};

/** A reference typed by a person, in the lowercase form the server accepts ("R/001" becomes "r-001"). */
export function reference(value: string): string {
  return value
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9._-]+/g, '-')
    .replace(/^[^a-z0-9]+/, '')
    .slice(0, 64);
}
export type Payload = Record<string, FormDataConvertible>;

export const choices = (values: string[]): [string, string][] =>
  values.map((v) => [v, v]);

export const evidence: Field = {
  name: 'evidence',
  label: 'Reason and evidence reference',
};

/** A collapsible card; what it holds sits inside without boxes of its own. */
export function Panel({
  title,
  description,
  open,
  children,
}: {
  title: string;
  description?: string;
  open?: boolean;
  children: ReactNode;
}) {
  const __ = useTrans();
  return (
    <details
      className="group bg-card text-card-foreground rounded-xl border shadow-xs shadow-black/5"
      open={open}
    >
      <summary className="focus-visible:ring-ring/30 flex min-h-14 cursor-pointer list-none items-center justify-between gap-3 rounded-xl px-5 py-4 outline-none focus-visible:ring-[3px] [&::-webkit-details-marker]:hidden">
        <span className="min-w-0 space-y-1.5">
          <span className="block text-base leading-none font-semibold tracking-tight">
            {__(title)}
          </span>
          {description && (
            <span className="text-muted-foreground block text-sm">
              {__(description)}
            </span>
          )}
        </span>
        <ChevronDown
          className="text-muted-foreground size-4 shrink-0 transition-transform group-open:rotate-180"
          aria-hidden="true"
        />
      </summary>
      <div className="divide-y border-t px-5 [&>*]:py-5">{children}</div>
    </details>
  );
}

/** A native select drawn like the system's inputs, so it sits level with them. */
export function NativeSelect({
  className,
  ...props
}: ComponentProps<'select'>) {
  return (
    <div className="relative min-w-0">
      <select
        data-slot="select"
        className={cn(
          'border-input bg-background text-foreground focus-visible:border-ring focus-visible:ring-ring/30 aria-invalid:border-destructive/60 block h-8.5 w-full min-w-0 cursor-pointer appearance-none truncate rounded-md border ps-3 pe-9 text-[0.8125rem] leading-(--text-sm--line-height) shadow-xs shadow-black/5 transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-60',
          className,
        )}
        {...props}
      />
      <ChevronDown
        className="text-muted-foreground pointer-events-none absolute end-3 top-1/2 size-4 -translate-y-1/2"
        aria-hidden="true"
      />
    </div>
  );
}

/** One question on a form: its label, the control, and any help below it. */
export function FormRow({
  id,
  label,
  hint,
  optional = false,
  className,
  children,
}: {
  id: string;
  label: string;
  hint?: string;
  optional?: boolean;
  className?: string;
  children: ReactNode;
}) {
  const __ = useTrans();
  return (
    <div className={cn('min-w-0 space-y-2', className)}>
      <Label htmlFor={id} className="block">
        {__(label)}
        {optional && (
          <span className="text-muted-foreground ms-1.5 text-xs leading-[0] font-normal">
            {__('Optional')}
          </span>
        )}
      </Label>
      {children}
      {hint && (
        <p
          id={`${id}-hint`}
          className="text-muted-foreground text-xs leading-relaxed"
        >
          {__(hint)}
        </p>
      )}
    </div>
  );
}

/**
 * The grid every savings form uses: two columns once there is room, and an odd number of
 * questions finishes on a row of three, so no question is left alone beside an empty column.
 */
export const formGrid = 'grid gap-x-4 gap-y-5 @lg/form:grid-cols-6';

export function span(index: number, count: number): string {
  if (count % 2 === 1 && count >= 3 && index >= count - 3)
    return '@lg/form:col-span-2';
  return '@lg/form:col-span-3';
}

/** A small form that posts one savings operation and shows the server's error. */
export function Operation({
  title,
  description,
  operation,
  fields = [],
  build = (v) => v,
  endpoint = '/savings',
  heading = true,
}: {
  title: string;
  /** What the operation does, under its heading. */
  description?: string;
  /** Off when the surrounding section already names the action. */
  heading?: boolean;
  operation: string;
  fields?: Field[];
  build?: (v: Record<string, string>) => Payload;
  endpoint?: string;
}) {
  const __ = useTrans();
  const id = useId();
  const form = useForm<Record<string, string>>({
    defaultValues: Object.fromEntries(
      fields.map((f) => [f.name, f.value ?? '']),
    ),
  });
  const action = useInertiaForm(form);
  const [error, setError] = useState('');
  // One generated reference per entry, kept across retries so a repeated submit is never recorded twice.
  const [generated, setGenerated] = useState(() => crypto.randomUUID());
  const typed = form.watch();
  const shown = fields.filter((f) => !f.show || f.show(typed));
  const single = shown.length === 1;
  const control = (f: Field, index: number) => {
    const fieldId = `${id}-${f.name}`;
    const common = {
      id: fieldId,
      required: !f.optional,
      'aria-describedby': f.hint ? `${fieldId}-hint` : undefined,
      ...form.register(f.name),
    };
    return (
      <FormRow
        key={f.name}
        id={fieldId}
        label={f.label}
        hint={f.hint}
        optional={f.optional}
        className={single ? 'w-full max-w-xs' : span(index, shown.length)}
      >
        {f.options ? (
          <NativeSelect {...common}>
            <option value="">{__('Select')}</option>
            {f.options.map(([v, label]) => (
              <option value={v} key={v}>
                {__(label)}
              </option>
            ))}
          </NativeSelect>
        ) : (
          <Input
            {...common}
            type={f.type ?? (f.name.includes('date') ? 'date' : 'text')}
            inputMode={f.name === 'amount' ? 'decimal' : undefined}
            maxLength={2000}
          />
        )}
      </FormRow>
    );
  };
  const submit = (
    <Button type="submit" disabled={action.processing} className="shrink-0">
      {action.processing && <LoaderCircle className="size-4 animate-spin" />}
      {__(title)}
    </Button>
  );
  return (
    <form
      className="@container/form flex h-full min-w-0 flex-col gap-4"
      onSubmit={form.handleSubmit((values) => {
        setError('');
        const v = { ...values };
        for (const f of fields) {
          if (f.show && !f.show(values)) v[f.name] = '';
          else if (f.auto)
            v[f.name] =
              reference(v[f.name] ?? '') ||
              `${operation}-${generated}`.slice(0, 64);
          else if (f.fallback && !(v[f.name] ?? '').trim())
            v[f.name] = __(f.fallback);
          // People type amounts as "20,000" or "20 000".
          if (f.name === 'amount')
            v[f.name] = (v[f.name] ?? '').replace(/[\s,]/g, '');
        }
        action.submit(
          'post',
          endpoint,
          { ...build(v), operation },
          {
            preserveScroll: true,
            onSuccess: () => {
              if (fields.some((f) => f.auto)) {
                setGenerated(crypto.randomUUID());
                form.reset();
              }
            },
            onError: (errors) => setError(Object.values(errors).join(' ')),
          },
        );
      })}
    >
      {(heading || description) && (
        <div className="space-y-1">
          {heading && (
            <h3 className="text-sm leading-6 font-semibold">{__(title)}</h3>
          )}
          {description && (
            <p className="text-muted-foreground text-sm">{__(description)}</p>
          )}
        </div>
      )}
      {single ? (
        <div className="mt-auto flex flex-wrap items-end gap-3">
          {control(shown[0], 0)}
          {submit}
        </div>
      ) : (
        <>
          {shown.length > 0 && (
            <div className={formGrid}>{shown.map(control)}</div>
          )}
          <div className="mt-auto flex flex-wrap gap-2 pt-1">{submit}</div>
        </>
      )}
      {error && (
        <p role="alert" className="text-destructive text-sm break-words">
          {error}
        </p>
      )}
    </form>
  );
}
