import { useState } from 'react';
import { BadgeCheck, LoaderCircleIcon, Search, UserPlus } from 'lucide-react';
import { Link } from '@rutatiina/ui/components/common/link';
import {
  Alert,
  AlertContent,
  AlertDescription,
  AlertIcon,
  AlertTitle,
} from '@rutatiina/ui/components/ui/alert';
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 { useTrans } from '@rutatiina/ui/lib/translations';
import { PersonFields } from '@nugsoft/people/components/person-fields';
import type { PersonDetails } from '@nugsoft/people/types';
import { json } from '@nugsoft/members/lib/http';
import type { Errors } from '@nugsoft/members/components/fields';
import type { Option } from '@nugsoft/members/types';

export type PersonInput = PersonDetails & {
  mode: 'link' | 'register' | '';
  /** The member record this person already has here, which stops a second registration. */
  existing?: string;
};

export const blankPerson: PersonInput = {
  mode: '',
  surname: '',
  given_names: '',
  other_names: '',
  sex: '',
  date_of_birth: '',
  nationality: 'UG',
  nin: '',
  tin: '',
};

type Lookup =
  | { found: false }
  | {
      found: true;
      preview: string;
      is_verified: boolean;
      member: {
        label: string;
        status_label: string;
        url: string | null;
      } | null;
    };

/**
 * Who the person is: looked up by their exact NIN first, so someone already in the
 * shared register is linked rather than registered again; otherwise their details are
 * entered as on their identity document.
 */
export function PersonPicker({
  id,
  value,
  onChange,
  errors,
  sexes,
}: {
  id: string;
  value: PersonInput;
  onChange: (value: PersonInput) => void;
  errors: Errors;
  sexes: Option[];
}) {
  const __ = useTrans();
  const [nin, setNin] = useState(value.nin);
  const [lookup, setLookup] = useState<Lookup | null>(null);
  const [checking, setChecking] = useState(false);
  const [failure, setFailure] = useState<string | null>(null);

  const search = async () => {
    setChecking(true);
    setFailure(null);

    try {
      const result = await json<Lookup>('/members/lookup', {
        method: 'POST',
        body: { nin },
      });
      setLookup(result);
      onChange(
        result.found
          ? {
              ...blankPerson,
              mode: 'link',
              nin,
              ...(result.member ? { existing: result.member.label } : {}),
            }
          : { ...blankPerson, mode: 'register', nin },
      );
    } catch (error) {
      setFailure((error as Error).message);
    } finally {
      setChecking(false);
    }
  };

  if (value.mode === 'register') {
    return (
      <div className="flex flex-col gap-4">
        <div className="flex flex-wrap items-center justify-between gap-2">
          <p className="text-muted-foreground text-sm">
            {value.nin
              ? __(
                  'Nobody with this NIN is registered yet. Enter the details as on the identity document.',
                )
              : __('Enter the details as on the identity document.')}
          </p>
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={() => {
              setLookup(null);
              onChange(blankPerson);
            }}
          >
            {__('Look up another NIN')}
          </Button>
        </div>
        <PersonFields
          values={value}
          onChange={(details) => onChange({ ...details, mode: 'register' })}
          errors={errors}
          sexes={sexes}
        />
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-3">
      <Label htmlFor={`${id}-nin`}>{__('NIN')}</Label>
      <div className="flex flex-col gap-2 sm:flex-row">
        <Input
          id={`${id}-nin`}
          autoComplete="off"
          className="uppercase sm:max-w-xs"
          value={nin}
          aria-invalid={!!errors.nin}
          placeholder={__('National identification number')}
          onChange={(event) => {
            setNin(event.target.value);
            setLookup(null);
            if (value.mode) onChange(blankPerson);
          }}
          onKeyDown={(event) => {
            if (event.key === 'Enter') {
              event.preventDefault();
              if (nin.trim().length >= 8) void search();
            }
          }}
        />
        <Button
          type="button"
          variant="outline"
          disabled={checking || nin.trim().length < 8}
          onClick={() => void search()}
        >
          {checking ? (
            <LoaderCircleIcon className="animate-spin" />
          ) : (
            <Search />
          )}
          {__('Look up')}
        </Button>
      </div>
      {(errors.nin || failure) && (
        <p className="text-destructive text-sm">{errors.nin ?? failure}</p>
      )}
      {lookup?.found && (
        <Alert variant={lookup.member ? 'warning' : 'info'} appearance="light">
          <AlertIcon>
            <BadgeCheck />
          </AlertIcon>
          <AlertContent>
            <AlertTitle>{lookup.preview}</AlertTitle>
            <AlertDescription>
              {lookup.member ? (
                <>
                  {__('Already registered here: :member (:status).', {
                    member: lookup.member.label,
                    status: lookup.member.status_label,
                  })}{' '}
                  {lookup.member.url && (
                    <Link
                      href={lookup.member.url}
                      className="font-medium underline"
                    >
                      {__('Open the record')}
                    </Link>
                  )}
                </>
              ) : lookup.is_verified ? (
                __(
                  'Registered and verified in the shared register. Their official details will be linked.',
                )
              ) : (
                __(
                  'Registered in the shared register, not verified yet. Their details will be linked.',
                )
              )}
            </AlertDescription>
          </AlertContent>
        </Alert>
      )}
      <button
        type="button"
        className="text-primary inline-flex items-center gap-1 self-start text-sm hover:underline"
        onClick={() => onChange({ ...blankPerson, mode: 'register', nin: '' })}
      >
        <UserPlus className="size-3.5" />
        {__('The person has no NIN')}
      </button>
    </div>
  );
}
