import {
  Alert,
  Button,
  Group,
  Loader,
  Stack,
  Text,
  TextInput,
} from "@mantine/core";
import type { UseFormRegisterReturn } from "react-hook-form";
import { AlertCircle, CheckCircle2, Download } from "lucide-react";
import { useETradeData } from "@/hooks/useETradeData";
import type { CompanyRegistrationData } from "@edr/types";

interface ETradeInfoProps {
  /** Current TIN value (drives button enablement). */
  tin: string;
  /** RHF registration for the TIN input — this is the form's primary TIN field. */
  register: UseFormRegisterReturn;
  /** Validation error for the TIN field, if any. */
  error?: string;
  onDataLoaded: (data: CompanyRegistrationData) => void;
}

export default function ETradeInfo({
  tin,
  register,
  error,
  onDataLoaded,
}: ETradeInfoProps) {
  const mutation = useETradeData();
  const isLoading = mutation.isPending;
  const hasData = mutation.data;

  const handleFetch = async () => {
    if (!tin || tin.length !== 10 || !tin.startsWith("00")) return;
    const result = await mutation.mutateAsync(tin);
    if (result) {
      onDataLoaded(result);
    }
  };

  const errorMessage =
    mutation.isError && mutation.error
      ? (mutation.error as any).message ||
        "Failed to fetch company information. Please try again."
      : null;

  return (
    <Stack gap="md">
      <Group align="flex-start" grow>
        <TextInput
          label={<>TIN Number (10 digits) <span style={{ color: "var(--mantine-color-red-6)" }}>*</span></>}
          placeholder="0012345678"
          maxLength={10}
          error={error}
          {...register}
        />
        <Button
          variant="filled"
          color="edr-green"
          onClick={handleFetch}
          disabled={!tin || tin.length !== 10 || !tin.startsWith("00") || isLoading}
          leftSection={
            isLoading ? <Loader size={16} /> : <Download size={16} />
          }
          mt="24px"
        >
          {isLoading ? "Getting..." : "Get Data"}
        </Button>
      </Group>

      {errorMessage && (
        <Alert
          icon={<AlertCircle size={16} />}
          color="red"
          title="Failed to fetch data"
        >
          {errorMessage} You can still fill in the details manually below.
        </Alert>
      )}

      {hasData && (
        <Alert
          icon={<CheckCircle2 size={16} />}
          color="green"
          title="Company information loaded"
        >
          <Stack gap={0}>
            <Text size="sm">
              <strong>License:</strong> {hasData.licenceNumber}
            </Text>
            <Text size="sm">
              <strong>Status:</strong> {hasData.statusDescription}
            </Text>
            {hasData.region && (
              <Text size="sm">
                <strong>Location:</strong> {hasData.kebele}, {hasData.woreda},{" "}
                {hasData.zone}, {hasData.region}
              </Text>
            )}
          </Stack>
        </Alert>
      )}
    </Stack>
  );
}
