import { FormEvent, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { AlertCircle, ArrowLeft, Building2, Loader2 } from "lucide-react";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { useAuth } from "@/shared/context/AuthContext";
import { registerWithEtrade } from "@/shared/services/authService";
import { persistFaydaRegistrationAuth } from "@/shared/utils/faydaAuthSession";
import { ComplaintPageLayout } from "../components/ComplaintPageLayout";
import { TinRegistrationNotFoundError } from "../services/complaintVerificationService";
import { storeComplaintVerification } from "../utils/complaintVerificationStorage";
import { COMPLAINT_RECORDS_PATH } from "../utils/complaintRoutes";
import type { VerifiedOrganization } from "../types/complaint.types";
import {
  EtradeBusinessLicenseOption,
  fetchRegistrationByTin,
  mapEtradeBusinessLicenses,
  mapEtradeRegistration,
  resolveEtradeLanguage,
  resolveEtradePhoneForSignup,
} from "../services/etradeTinService";
import { EtradeLicensePicker } from "@/shared/components/etrade/EtradeLicensePicker";

type VerificationStep = "tin" | "select_license";

export default function ComplaintTinVerificationPage() {
  const { t, i18n } = useTranslation();
  const navigate = useNavigate();
  const { setUser, setSelectedPositionId } = useAuth();
  const { handleError, getErrorMessage } = useErrorHandler(t);
  const [step, setStep] = useState<VerificationStep>("tin");
  const [tin, setTin] = useState("");
  const [organization, setOrganization] = useState<VerifiedOrganization | null>(
    null,
  );
  const [organizationName, setOrganizationName] = useState("");
  const [licenseOptions, setLicenseOptions] = useState<
    EtradeBusinessLicenseOption[]
  >([]);
  const [selectedLicenseNumber, setSelectedLicenseNumber] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [isVerifying, setIsVerifying] = useState(false);
  const [isContinuing, setIsContinuing] = useState(false);

  const handleVerify = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError(null);

    const normalizedTin = tin.trim();
    if (!normalizedTin) {
      setError(t("complaint.tin.tinRequired"));
      return;
    }

    if (!/^\d{10}$/.test(normalizedTin)) {
      setError(t("complaint.tin.tinInvalid"));
      return;
    }

    try {
      setIsVerifying(true);
      const registration = await fetchRegistrationByTin(
        normalizedTin,
        resolveEtradeLanguage(i18n.language),
      );
      const verifiedOrganization = mapEtradeRegistration(
        registration,
        normalizedTin,
      );

      if (!verifiedOrganization.organizationName && !verifiedOrganization.tin) {
        setError(t("complaint.tin.notFound"));
        return;
      }

      const businesses = mapEtradeBusinessLicenses(
        registration,
        resolveEtradeLanguage(i18n.language),
      );

      if (businesses.length === 0) {
        setError(t("registration.etrade.noLicensesFound"));
        return;
      }

      setOrganization(verifiedOrganization);
      setOrganizationName(verifiedOrganization.organizationName);
      setLicenseOptions(businesses);
      setSelectedLicenseNumber(businesses[0].licenseNumber);
      setStep("select_license");
    } catch (verifyError) {
      if (verifyError instanceof TinRegistrationNotFoundError) {
        setError(t("complaint.tin.notFound"));
        return;
      }
      if (
        verifyError instanceof Error &&
        verifyError.message === "ETRADE_REFERER_REJECTED"
      ) {
        setError(t("complaint.tin.proxyError"));
        return;
      }
      setError(await getErrorMessage(verifyError));
    } finally {
      setIsVerifying(false);
    }
  };

  const handleLicenseContinue = async () => {
    if (!organization || !selectedLicenseNumber) return;

    const selectedLicense = licenseOptions.find(
      (option) => option.licenseNumber === selectedLicenseNumber,
    );
    if (!selectedLicense) return;

    try {
      setIsContinuing(true);
      setError(null);

      let phoneNumber: string | undefined;
      try {
        phoneNumber =
          (await resolveEtradePhoneForSignup(
            selectedLicense.licenseNumber,
            organization.tin,
            resolveEtradeLanguage(i18n.language),
          )) ?? undefined;
      } catch (phoneError) {
        console.warn(
          "[complaint:eTrade] Failed to resolve phone from GetBusinessByLicenseNo",
          phoneError,
        );
      }

      if (!phoneNumber) {
        setError(t("registration.etrade.phoneLookupFailed"));
        return;
      }

      const registrationResponse = await registerWithEtrade({
        tin: organization.tin,
        licenseNumber: selectedLicense.licenseNumber,
        phoneNumber,
      });
      const registration = registrationResponse.data;

      if (!registration?.token?.trim()) {
        setError(t("complaint.tin.registrationFailed"));
        return;
      }

      const profile = await persistFaydaRegistrationAuth(registration);
      if (profile) {
        setUser(profile);
        const firstPositionId =
          profile.employee?.[0]?.positions?.[0]?.employeePositionId;
        if (firstPositionId) {
          setSelectedPositionId(firstPositionId);
        }
      }

      storeComplaintVerification({
        verified: true,
        method: "tin",
        organization: {
          ...organization,
          licenseNumber: selectedLicense.licenseNumber,
          tradeName: selectedLicense.tradeName,
          mainGuid: selectedLicense.mainGuid,
        },
        verifiedAt: new Date().toISOString(),
        registration,
      });

      navigate(COMPLAINT_RECORDS_PATH, {
        replace: true,
        state: { fromComplaintVerification: true },
      });
    } catch (continueError) {
      handleError(continueError);
    } finally {
      setIsContinuing(false);
    }
  };

  return (
    <ComplaintPageLayout
      heroTitle={t("registration.auth.continueWithEtrade")}
      heroSubtitle={t("complaint.tin.subtitle")}>
      <div className="w-full max-w-xl rounded-2xl border border-gray-200 bg-white p-6 md:p-8">
        <Link
          to="/complaints"
          className="mb-6 inline-flex items-center gap-2 text-sm font-medium text-gray-600 hover:text-primary">
          <ArrowLeft className="h-4 w-4" />
          {t("complaint.back")}
        </Link>

        <div className="mb-6 flex items-start gap-4">
          <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-amber-50 text-amber-600">
            <Building2 className="h-6 w-6" />
          </div>
          <div>
            <h2 className="text-lg font-semibold text-gray-900">
              {step === "tin"
                ? t("complaint.tin.formTitle")
                : t("registration.etrade.selectLicenseTitle")}
            </h2>
            <p className="mt-1 text-sm text-gray-600">
              {step === "tin"
                ? t("complaint.tin.formDescription")
                : t("registration.etrade.selectLicenseDescription")}
            </p>
          </div>
        </div>

        {error && (
          <div className="mb-6 flex items-start gap-3 rounded-lg border border-red-200 bg-red-50 p-4">
            <AlertCircle className="mt-0.5 h-5 w-5 shrink-0 text-red-500" />
            <p className="text-sm text-red-700">{error}</p>
          </div>
        )}

        {step === "tin" ? (
          <form onSubmit={handleVerify} className="space-y-6">
            <div className="space-y-2">
              <Label htmlFor="tin">{t("complaint.tin.tinLabel")}</Label>
              <Input
                id="tin"
                inputMode="numeric"
                pattern="\d*"
                maxLength={10}
                value={tin}
                onChange={(event) =>
                  setTin(event.target.value.replace(/\D/g, "").slice(0, 10))
                }
                placeholder={t("complaint.tin.tinPlaceholder")}
                className="font-mono text-lg tracking-wide"
                autoComplete="off"
                disabled={isVerifying}
                required
              />
              <p className="text-xs text-gray-500">
                {t("complaint.tin.tinHint")}
              </p>
            </div>

            <Button
              type="submit"
              disabled={isVerifying || tin.trim().length !== 10}
              className="w-full py-6 text-base font-semibold">
              {isVerifying ? (
                <span className="flex items-center justify-center gap-2">
                  <Loader2 className="h-5 w-5 animate-spin" />
                  {t("complaint.tin.verifying")}
                </span>
              ) : (
                t("complaint.tin.verify")
              )}
            </Button>
          </form>
        ) : (
          <div className="space-y-6">
            <EtradeLicensePicker
              organizationName={organizationName}
              options={licenseOptions}
              selectedLicenseNumber={selectedLicenseNumber}
              onSelect={setSelectedLicenseNumber}
            />

            <div className="flex justify-center gap-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => {
                  setStep("tin");
                  setSelectedLicenseNumber("");
                  setLicenseOptions([]);
                  setOrganization(null);
                  setOrganizationName("");
                }}
                disabled={isContinuing}>
                {t("registration.etrade.back")}
              </Button>
              <Button
                type="button"
                onClick={handleLicenseContinue}
                disabled={!selectedLicenseNumber || isContinuing}
                className="min-w-[8rem]">
                {isContinuing ? (
                  <span className="flex items-center gap-2">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    {t("registration.etrade.loading")}
                  </span>
                ) : (
                  t("registration.etrade.continue")
                )}
              </Button>
            </div>
          </div>
        )}
      </div>
    </ComplaintPageLayout>
  );
}
