import { useId, 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 { useTrans } from '@rutatiina/ui/lib/translations';
import type { Props } from '@nugsoft/savings/lib/types';
import { FormRow, formGrid, NativeSelect, span } from '@nugsoft/savings/lib/ui';

type Preview = {
  rows: {
    line: number;
    account_number: string;
    member?: string;
    amount: string;
    error: string | null;
  }[];
  count: number;
  errors: number;
  total: string;
};

/** Upload a CSV of deposits: check it first, then post every row or none. */
export function Batches({ props }: { props: Props }) {
  const __ = useTrans();
  const id = useId();
  const [file, setFile] = useState<File | null>(null);
  const [date, setDate] = useState(props.date);
  const [key, setKey] = useState('');
  const [channel, setChannel] = useState('cash');
  const [custody, setCustody] = useState(
    String(
      props.custodies.find((c) => c.holder_id === props.actorId)?.id ?? '',
    ),
  );
  const [reference, setReference] = useState('');
  const [evidence, setEvidence] = useState('');
  const [preview, setPreview] = useState<Preview | null>(null);
  const [error, setError] = useState('');
  const check = async (event: FormEvent) => {
    event.preventDefault();
    if (!file) return;
    setError('');
    const data = new FormData();
    data.append('file', file);
    data.append('date', date);
    const token = document.cookie
      .split('; ')
      .find((e) => e.startsWith('XSRF-TOKEN='));
    const response = await fetch('/savings/batches/preview', {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
        Accept: 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        ...(token
          ? { 'X-XSRF-TOKEN': decodeURIComponent(token.slice(11)) }
          : {}),
      },
      body: data,
    });
    const body = await response.json();
    if (!response.ok) {
      setError(
        Object.values(body.errors ?? {})
          .flat()
          .join(' ') || body.message,
      );
      setPreview(null);
      return;
    }
    setPreview(body);
  };
  const post = () => {
    if (!file) return;
    router.post(
      '/savings/batches',
      { file, date, key, channel, custody_id: custody, reference, evidence },
      {
        forceFormData: true,
        preserveScroll: true,
        onError: (errors) => setError(Object.values(errors).join(' ')),
        onSuccess: () => setPreview(null),
      },
    );
  };
  const fields = [
    <FormRow id={`${id}-file`} label="CSV file" key="file">
      <Input
        id={`${id}-file`}
        type="file"
        accept=".csv,text/csv"
        required
        onChange={(e) => setFile(e.target.files?.[0] ?? null)}
      />
    </FormRow>,
    <FormRow id={`${id}-date`} label="Deposit date" key="date">
      <Input
        id={`${id}-date`}
        type="date"
        value={date}
        required
        onChange={(e) => setDate(e.target.value)}
      />
    </FormRow>,
    <FormRow
      id={`${id}-key`}
      label="Batch reference"
      hint="Needed to post the file; the same reference never posts twice."
      key="key"
    >
      <Input
        id={`${id}-key`}
        value={key}
        maxLength={48}
        aria-describedby={`${id}-key-hint`}
        onChange={(e) => setKey(e.target.value)}
      />
    </FormRow>,
    <FormRow id={`${id}-channel`} label="Money received by" key="channel">
      <NativeSelect
        id={`${id}-channel`}
        value={channel}
        onChange={(e) => setChannel(e.target.value)}
      >
        <option value="cash">{__('Cash')}</option>
        <option value="bank">{__('Bank or mobile money')}</option>
      </NativeSelect>
    </FormRow>,
    channel === 'cash' ? (
      <FormRow id={`${id}-custody`} label="Cash drawer" key="custody">
        <NativeSelect
          id={`${id}-custody`}
          value={custody}
          onChange={(e) => setCustody(e.target.value)}
        >
          <option value="">{__('Select')}</option>
          {props.custodies.map((c) => (
            <option value={c.id} key={c.id}>
              {c.label}
            </option>
          ))}
        </NativeSelect>
      </FormRow>
    ) : (
      <FormRow
        id={`${id}-reference`}
        label="Bank or mobile-money reference"
        key="reference"
      >
        <Input
          id={`${id}-reference`}
          value={reference}
          onChange={(e) => setReference(e.target.value)}
        />
      </FormRow>
    ),
    <FormRow
      id={`${id}-evidence`}
      label="Narration"
      hint="Needed to post the file, for example where the list came from."
      key="evidence"
    >
      <Input
        id={`${id}-evidence`}
        value={evidence}
        maxLength={500}
        aria-describedby={`${id}-evidence-hint`}
        onChange={(e) => setEvidence(e.target.value)}
      />
    </FormRow>,
  ];
  return (
    <section className="space-y-5">
      <p className="text-muted-foreground text-sm">
        {__(
          'One row per deposit: account number, amount, reference and narration.',
        )}{' '}
        <a
          className="text-primary font-medium hover:underline"
          href="/savings/batches/template"
        >
          {__('Download the template')}
        </a>
      </p>
      <form
        className="@container/form space-y-5"
        onSubmit={(e) => void check(e)}
      >
        <div className={formGrid}>
          {fields.map((field, index) => (
            <div className={span(index, fields.length)} key={field.key}>
              {field}
            </div>
          ))}
        </div>
        <div className="flex flex-wrap gap-2">
          <Button
            type="submit"
            variant={preview && preview.errors === 0 ? 'outline' : 'primary'}
            disabled={!file}
          >
            {__('Check file')}
          </Button>
          {preview && preview.errors === 0 && (
            <Button type="button" onClick={post} disabled={!key || !evidence}>
              {__('Post :count deposits (UGX :total)', {
                count: preview.count,
                total: preview.total,
              })}
            </Button>
          )}
        </div>
      </form>
      {error && (
        <p role="alert" className="text-destructive text-sm break-words">
          {error}
        </p>
      )}
      {preview && (
        <div className="overflow-x-auto rounded-lg border">
          <table className="w-full text-start text-sm">
            <thead className="bg-muted/50 text-muted-foreground">
              <tr className="border-b">
                {['Line', 'Account', 'Member', 'Amount (UGX)', 'Check'].map(
                  (h) => (
                    <th className="px-3 py-2 text-start font-medium" key={h}>
                      {__(h)}
                    </th>
                  ),
                )}
              </tr>
            </thead>
            <tbody className="divide-y">
              {preview.rows.map((r) => (
                <tr key={r.line}>
                  <td className="px-3 py-2">{r.line}</td>
                  <td className="px-3 py-2">{r.account_number}</td>
                  <td className="px-3 py-2">{r.member ?? ''}</td>
                  <td className="px-3 py-2 tabular-nums">{r.amount}</td>
                  <td
                    className={`px-3 py-2 ${r.error ? 'text-destructive' : 'text-primary'}`}
                  >
                    {r.error ?? __('OK')}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </section>
  );
}
