import { useState, type FormEvent } from 'react';
import { router } from '@inertiajs/react';
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 { formatDateTime } from '@rutatiina/ui/lib/helpers';
import { useTrans } from '@rutatiina/ui/lib/translations';
import type { Application, AssessmentData } from '@nugsoft/loans/lib/types';

/** Supporting documents for an application, with the product's missing types and an upload form. */
export function Documents({
  application,
  canUpload,
}: {
  application: Application;
  canUpload: boolean;
}) {
  const __ = useTrans();
  const [type, setType] = useState(application.missing_documents[0] ?? '');
  const [file, setFile] = useState<File | null>(null);
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);
  const submit = (event: FormEvent) => {
    event.preventDefault();
    if (!file) return;
    setError('');
    setBusy(true);
    router.post(
      '/loans/documents',
      { key: application.application_key, type, file },
      {
        forceFormData: true,
        preserveScroll: true,
        onError: (errors) => setError(Object.values(errors).join(' ')),
        onSuccess: () => setFile(null),
        onFinish: () => setBusy(false),
      },
    );
  };
  return (
    <details className="space-y-2">
      <summary className="cursor-pointer">
        {__('Documents')} ({application.documents.length})
        {application.missing_documents.length > 0 &&
          ` · ${__('missing')}: ${application.missing_documents.join(', ')}`}
      </summary>
      <ul className="text-sm">
        {application.documents.map((d) => (
          <li key={d.id}>
            <a
              className="underline"
              href={`/loans/documents/${d.id}`}
              target="_blank"
              rel="noreferrer"
            >
              {d.type}: {d.original_name}
            </a>{' '}
            · {Math.ceil(d.size / 1024)} KB · {formatDateTime(d.created_at)}
          </li>
        ))}
      </ul>
      {canUpload && (
        <form
          className="grid gap-3 rounded border p-3 sm:grid-cols-3"
          onSubmit={submit}
        >
          <Label className="block space-y-1">
            <span>{__('Document type')}</span>
            <Input
              list={`types-${application.id}`}
              value={type}
              required
              onChange={(e) => setType(e.target.value)}
            />
            <datalist id={`types-${application.id}`}>
              {application.required_documents.map((t) => (
                <option value={t} key={t} />
              ))}
            </datalist>
          </Label>
          <Label className="block space-y-1">
            <span>{__('File (PDF or image)')}</span>
            <Input
              type="file"
              accept=".pdf,.jpg,.jpeg,.png,.webp"
              required
              onChange={(e) => setFile(e.target.files?.[0] ?? null)}
            />
          </Label>
          <div className="flex items-end">
            <Button disabled={busy || !file}>{__('Upload document')}</Button>
          </div>
          {error && (
            <p role="alert" className="text-destructive sm:col-span-3">
              {error}
            </p>
          )}
        </form>
      )}
    </details>
  );
}

/** The officer's structured assessment, or the free text of older applications. */
export function AssessmentView({
  data,
  text,
}: {
  data: AssessmentData | null;
  text: string;
}) {
  const __ = useTrans();
  if (!data) return <p className="break-words">{text}</p>;
  return (
    <dl className="grid gap-2 text-sm sm:grid-cols-3">
      <div>
        <dt className="text-muted-foreground">{__('Purpose')}</dt>
        <dd>{data.purpose}</dd>
      </div>
      <div>
        <dt className="text-muted-foreground">
          {__('Officer recommendation')}
        </dt>
        <dd>{__(data.recommendation)}</dd>
      </div>
      <div>
        <dt className="text-muted-foreground">
          {__('Monthly income / expenses / other loans (UGX)')}
        </dt>
        <dd>
          {data.income ?? '—'} / {data.expenses ?? '—'} / {data.debts ?? '—'}
        </dd>
      </div>
      <div>
        <dt className="text-muted-foreground">
          {__('Monthly installment (UGX)')}
        </dt>
        <dd>{data.capacity.installment_monthly}</dd>
      </div>
      <div>
        <dt className="text-muted-foreground">
          {__('Net monthly income (UGX)')}
        </dt>
        <dd>{data.capacity.net_income ?? '—'}</dd>
      </div>
      <div>
        <dt className="text-muted-foreground">
          {__('Installment share of net income')}
        </dt>
        <dd>{data.capacity.ratio ? `${data.capacity.ratio}%` : '—'}</dd>
      </div>
      {data.notes && (
        <div className="sm:col-span-3">
          <dt className="text-muted-foreground">{__('Notes')}</dt>
          <dd className="break-words">{data.notes}</dd>
        </div>
      )}
    </dl>
  );
}
