import { type ReactNode, useState } from 'react';
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 { formatDate } from '@rutatiina/ui/lib/helpers';
import { useTrans } from '@rutatiina/ui/lib/translations';
import type {
  Components as Amounts,
  Field,
  Installment,
  Payload,
  Result,
} from '@nugsoft/loans/lib/types';
import { money } from '@nugsoft/accounting/components/openings/labels';

export const choices = (values: string[]): [string, string][] =>
  values.map((v) => [v, v]);
export const evidence: Field = {
  name: 'evidence',
  label: 'Assessment, reason and evidence reference',
};
export function Schedule({ rows }: { rows: Installment[] }) {
  const __ = useTrans();
  return (
    <div className="overflow-x-auto">
      <table className="w-full text-left text-sm">
        <thead>
          <tr>
            {[
              'Installment',
              'Due date',
              'Principal (UGX)',
              'Interest forecast (UGX)',
            ].map((s) => (
              <th className="p-2" key={s}>
                {__(s)}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((r) => (
            <tr className="border-t" key={r.number}>
              <td className="p-2">{r.number}</td>
              <td>{formatDate(r.date)}</td>
              <td>{r.principal}</td>
              <td>{r.interest}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
export function Operation({
  title,
  operation,
  fields = [],
  build = (v) => v,
  preview = false,
  confirmOperation,
  endpoint = '/loans',
  render,
  button,
}: {
  title: string;
  operation: string;
  fields?: Field[];
  build?: (v: Record<string, string>) => Payload;
  preview?: boolean;
  confirmOperation?: string;
  endpoint?: string;
  /** Shows a preview result in its own way instead of the standard quote summary. */
  render?: (result: Record<string, unknown>) => ReactNode;
  /** The submit button label, when it differs from the title. */
  button?: string;
}) {
  const __ = useTrans();
  const form = useForm<Record<string, string>>({
    defaultValues: Object.fromEntries(
      fields.map((f) => [f.name, f.value ?? '']),
    ),
  });
  const action = useInertiaForm(form);
  const [error, setError] = useState('');
  const [result, setResult] = useState<Result | null>(null);
  const [loading, setLoading] = useState(false);
  // One generated reference per entry, kept across retries so a repeated submit is never recorded twice.
  const [generated, setGenerated] = useState(() => crypto.randomUUID());
  const send = async (typed: Record<string, string>) => {
    setError('');
    setResult(null);
    const values = { ...typed };
    if (fields.some((f) => f.name === 'key'))
      // Any typed reference is made valid ("RCPT-0001" becomes "rcpt-0001"); a blank one is generated.
      values.key =
        (values.key ?? '')
          .trim()
          .toLowerCase()
          .replace(/[^a-z0-9._-]+/g, '-')
          .replace(/^[^a-z0-9]+/, '')
          .slice(0, 64) || `${operation}-${generated}`.slice(0, 64);
    // People type amounts as "110,000".
    for (const name of ['amount', 'principal'])
      if (values[name]) values[name] = values[name].replace(/[\s,]/g, '');
    const payload = { ...build(values), operation };
    if (!preview) {
      action.submit('post', endpoint, payload, {
        preserveScroll: true,
        onSuccess: () => {
          if (fields.some((f) => f.name === 'key')) {
            setGenerated(crypto.randomUUID());
            form.reset();
          }
        },
        onError: (errors) => setError(Object.values(errors).join(' ')),
      });
      return;
    }
    setLoading(true);
    try {
      const token = document.cookie
        .split('; ')
        .find((e) => e.startsWith('XSRF-TOKEN='));
      const response = await fetch(endpoint, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest',
          ...(token
            ? { 'X-XSRF-TOKEN': decodeURIComponent(token.slice(11)) }
            : {}),
        },
        body: JSON.stringify(payload),
      });
      const data = await response.json();
      if (!response.ok)
        throw new Error(
          Object.values(data.errors ?? {})
            .flat()
            .join(' ') || data.message,
        );
      setResult(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : __('Preview failed.'));
    } finally {
      setLoading(false);
    }
  };
  return (
    <form
      className="bg-background min-w-0 space-y-3 rounded-lg border p-4"
      onSubmit={form.handleSubmit((v) => void send(v))}
    >
      <h3 className="font-semibold">{__(title)}</h3>
      <div className="grid gap-3 sm:grid-cols-2">
        {fields.map((f) => (
          <Label className="block min-w-0 space-y-1" key={f.name}>
            <span>{__(f.label)}</span>
            {f.options ? (
              <select
                className="bg-background block w-full rounded border p-2"
                required={!f.optional}
                {...form.register(f.name)}
              >
                <option value="">{__('Select')}</option>
                {f.options.map(([v, label]) => (
                  <option value={v} key={v}>
                    {__(label)}
                  </option>
                ))}
              </select>
            ) : (
              <Input
                type={
                  f.name.includes('date') || f.name === 'first_due'
                    ? 'date'
                    : 'text'
                }
                required={!f.optional}
                maxLength={2000}
                {...form.register(f.name)}
              />
            )}
          </Label>
        ))}
      </div>
      {error && (
        <p role="alert" className="text-destructive break-words">
          {error}
        </p>
      )}
      <Button disabled={action.processing || loading}>
        {__(button ?? title)}
      </Button>
      {result && render && (
        <div aria-live="polite" className="bg-muted space-y-2 rounded p-3">
          {render(result as Record<string, unknown>)}
        </div>
      )}
      {result && !render && (
        <div aria-live="polite" className="bg-muted space-y-2 rounded p-3">
          {result.total && (
            <p>
              {__('Total (UGX)')}: {result.total}
            </p>
          )}
          {confirmOperation && result.checksum && (
            <>
              <p>
                {__('Reviewed scope')}: {result.date && formatDate(result.date)}{' '}
                · {__('Branches')}: {result.branches?.join(', ')} ·{' '}
                {result.required_providers?.join(', ')}
              </p>
              <Button
                type="button"
                disabled={action.processing}
                onClick={() =>
                  action.submit(
                    'post',
                    endpoint,
                    {
                      ...build(form.getValues()),
                      operation: confirmOperation,
                      checksum: result.checksum!,
                    },
                    {
                      preserveScroll: true,
                      onError: (errors) =>
                        setError(Object.values(errors).join(' ')),
                    },
                  )
                }
              >
                {__('Confirm reviewed lending activation')}
              </Button>
            </>
          )}
          {result.gross_principal && (
            <p>
              {__('Gross principal / net disbursement (UGX)')}:{' '}
              {result.gross_principal} / {result.net_disbursement}
            </p>
          )}
          {result.future_treatment && (
            <p>
              {__('Future interest policy')}: {__(result.future_treatment)}
            </p>
          )}
          {result.components &&
            Object.entries(result.components).map(([k, v]) => (
              <p key={k}>
                {__(k)}: {money('UGX', v)}
              </p>
            ))}
          {result.installments && <Schedule rows={result.installments} />}
        </div>
      )}
    </form>
  );
}
export function Components({ values }: { values: Amounts }) {
  const __ = useTrans();
  return (
    <div className="flex flex-wrap gap-4">
      {Object.entries(values).map(([k, v]) => (
        <p key={k}>
          <span className="capitalize">{__(k)}</span>:{' '}
          <strong>{money('UGX', v)}</strong>
        </p>
      ))}
    </div>
  );
}
