"use client";

import { FormEvent, useEffect, useState } from "react";
import {
  Building2,
  Loader2,
  AlertCircle,
  UserRound,
} from "lucide-react";
import { Button } from "@/shared/common/ui/button";
import { Card } from "@/shared/common/ui/card";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { Link } from "react-router-dom";
import VerifyOtp from "../verifyOTP";
import { useTradeLicenseVerification } from "@/external-portal/hooks/useTradeLicenseVerification";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import {
  startExternalPortalFaydaAuth,
} from "@/shared/utils/faydaOidc";
import {
  EtradeBusinessLicenseOption,
  fetchRegistrationByTin,
  mapEtradeBusinessLicenses,
  resolveEtradeLanguage,
  TinRegistrationNotFoundError,
} from "@/complaints/services/etradeTinService";
import {
  isValidLicenseNo,
  normalizeLicenseNo,
  normalizeTin,
} from "@/external-portal/utils/etradeValidation";
import {
  clearEtradeLicenseNo,
  storeEtradeLicenseNo,
} from "@/external-portal/utils/etradeAuthStorage";

type OrgStep = "trade_license" | null;
type TradeLicenseStep = "tin" | "select_license";

export default function UserTypeSelection() {
  const [orgStep, setOrgStep] = useState<OrgStep>(null);
  const [tradeLicenseStep, setTradeLicenseStep] =
    useState<TradeLicenseStep>("tin");
  const [tin, setTin] = useState("");
  const [organizationName, setOrganizationName] = useState("");
  const [licenseOptions, setLicenseOptions] = useState<
    EtradeBusinessLicenseOption[]
  >([]);
  const [selectedLicenseNumber, setSelectedLicenseNumber] = useState("");
  const [tradeLicenseNumber, setTradeLicenseNumber] = useState("");
  const [tinError, setTinError] = useState<string | null>(null);
  const [isVerifyingTin, setIsVerifyingTin] = useState(false);

  const { t, i18n } = useTranslation();
  const [showVerifyOtp, setShowVerifyOtp] = useState(false);
  const { handleError } = useErrorHandler(t);
  const { registerTradeLicense, isRegistering } = useTradeLicenseVerification();

  const resetTradeLicenseFlow = () => {
    setTradeLicenseStep("tin");
    setTin("");
    setOrganizationName("");
    setLicenseOptions([]);
    setSelectedLicenseNumber("");
    setTradeLicenseNumber("");
    setTinError(null);
    setShowVerifyOtp(false);
    clearEtradeLicenseNo();
  };

  useEffect(() => {
    setOrgStep(null);
    resetTradeLicenseFlow();
  }, []);

  const onVerifyComplete = () => {
    toast.success(t("registration.etrade.registrationSuccess"));
  };

  const registerWithLicense = async (licenseNumber: string) => {
    const normalizedLicense = normalizeLicenseNo(licenseNumber);
    if (!isValidLicenseNo(normalizedLicense)) return;

    setTradeLicenseNumber(normalizedLicense);
    storeEtradeLicenseNo(normalizedLicense);
    await registerTradeLicense({
      tin: normalizeTin(tin),
      licenseNo: normalizedLicense,
    });
    setShowVerifyOtp(true);
  };

  const startETradeAuth = () => {
    resetTradeLicenseFlow();
    setOrgStep("trade_license");
  };

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

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

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

    try {
      setIsVerifyingTin(true);
      const registration = await fetchRegistrationByTin(
        normalizedTin,
        resolveEtradeLanguage(i18n.language),
      );
      const businesses = mapEtradeBusinessLicenses(
        registration,
        resolveEtradeLanguage(i18n.language),
      );

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

      const companyName = String(
        registration.BusinessName ??
          registration.businessName ??
          registration.BusinessNameAmh ??
          registration.businessNameAmh ??
          "",
      ).trim();

      setOrganizationName(companyName);
      setLicenseOptions(businesses);
      setSelectedLicenseNumber(businesses[0].licenseNumber);
      setTradeLicenseStep("select_license");
    } catch (error) {
      if (error instanceof TinRegistrationNotFoundError) {
        setTinError(t("complaint.tin.notFound"));
        return;
      }
      if (
        error instanceof Error &&
        error.message === "ETRADE_REFERER_REJECTED"
      ) {
        setTinError(t("complaint.tin.proxyError"));
        return;
      }
      handleError(error);
    } finally {
      setIsVerifyingTin(false);
    }
  };

  const handleLicenseSelectionSubmit = async () => {
    if (!selectedLicenseNumber) return;

    try {
      await registerWithLicense(selectedLicenseNumber);
    } catch (error) {
      handleError(error);
    }
  };

  const authOptions = [
    {
      provider: "fayda" as const,
      title: t("registration.auth.continueWithFayda"),
      description: t("registration.auth.faydaDescription"),
      icon: UserRound,
      onClick: () => startExternalPortalFaydaAuth(),
    },
    {
      provider: "etrade" as const,
      title: t("registration.auth.continueWithEtrade"),
      description: t("registration.auth.etradeDescription"),
      icon: Building2,
      onClick: () => startETradeAuth(),
    },
  ];

  return (
    <div className="min-h-screen flex items-center justify-center bg-primary-50 p-4">
      <div className="w-full max-w-3xl">
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center gap-2 mb-4">
            <Building2 className="size-8 text-primary-600" />
            <h1 className="text-3xl font-bold text-primary-900">
              {t("registration.auth.portalTitle")}
            </h1>
          </div>
          <p className="text-primary-700 text-lg">
            {t("registration.auth.selectionDescription")}
          </p>
        </div>

        {!orgStep && (
          <>
            <div className="grid gap-6 md:grid-cols-2 mb-8">
              {authOptions.map((option) => {
                const Icon = option.icon;
                return (
                  <Card
                    key={option.provider}
                    className="p-6 cursor-pointer border-2 border-primary-200 bg-white transition-all hover:border-primary-400"
                    onClick={option.onClick}>
                    <div className="flex flex-col items-center text-center gap-4">
                      <div className="p-4 rounded-full bg-primary-100 text-primary-600">
                        <Icon className="size-8" />
                      </div>
                      <div>
                        <h2 className="text-xl font-semibold mb-2 text-primary-900">
                          {option.title}
                        </h2>
                        <p className="text-primary-700 text-sm">
                          {option.description}
                        </p>
                      </div>
                    </div>
                  </Card>
                );
              })}
            </div>

            <div className="text-center">
              <Link
                to="/login"
                className="text-sm font-medium text-primary-700 hover:text-primary-900 hover:underline">
                {t("registration.auth.employeeLogin")}
              </Link>
            </div>

            <div className="mt-4 text-center">
              <Link
                to="/external-portal/signup/manual"
                className="text-sm font-medium text-primary-700 hover:text-primary-900 hover:underline">
                {t("registration.auth.manualOrgSignup")}
              </Link>
            </div>
          </>
        )}

        {orgStep === "trade_license" && (
          <div className="mb-6 flex items-center justify-center gap-2 text-sm">
            <span
              className={`rounded-full px-3 py-1 ${
                tradeLicenseStep === "tin" && !showVerifyOtp
                  ? "bg-primary-600 text-white"
                  : "bg-primary-100 text-primary-700"
              }`}>
              1. {t("registration.etrade.stepTin")}
            </span>
            <span className="text-primary-400">→</span>
            <span
              className={`rounded-full px-3 py-1 ${
                tradeLicenseStep === "select_license" && !showVerifyOtp
                  ? "bg-primary-600 text-white"
                  : "bg-primary-100 text-primary-700"
              }`}>
              2. {t("registration.etrade.stepLicense")}
            </span>
            <span className="text-primary-400">→</span>
            <span
              className={`rounded-full px-3 py-1 ${
                showVerifyOtp
                  ? "bg-primary-600 text-white"
                  : "bg-primary-100 text-primary-700"
              }`}>
              3. {t("registration.etrade.stepOtp")}
            </span>
          </div>
        )}

        {orgStep === "trade_license" &&
          (!showVerifyOtp ? (
            tradeLicenseStep === "tin" ? (
              <div className="space-y-6">
                <div className="text-center">
                  <h2 className="text-2xl font-semibold text-primary-900">
                    {t("registration.auth.continueWithEtrade")}
                  </h2>
                  <p className="mt-2 text-sm text-primary-700">
                    {t("registration.etrade.enterTinDescription")}
                  </p>
                </div>

                {tinError && (
                  <div className="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">{tinError}</p>
                  </div>
                )}

                <form onSubmit={handleTinVerify} className="space-y-4">
                  <div className="space-y-2">
                    <Label htmlFor="etrade-tin">
                      {t("complaint.tin.tinLabel")}
                    </Label>
                    <Input
                      id="etrade-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="border-primary-300 focus:ring-primary-500 font-mono text-lg tracking-wide"
                      autoComplete="off"
                      disabled={isVerifyingTin}
                      required
                    />
                    <p className="text-xs text-primary-600">
                      {t("complaint.tin.tinHint")}
                    </p>
                  </div>

                  <div className="flex justify-center gap-4 pt-2">
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => setOrgStep(null)}
                      className="border-primary-400 text-primary-700 hover:bg-primary-100"
                      disabled={isVerifyingTin}>
                      {t("registration.etrade.back")}
                    </Button>
                    <Button
                      type="submit"
                      disabled={isVerifyingTin || tin.trim().length !== 10}
                      className="bg-primary-600 hover:bg-primary-700 text-white">
                      {isVerifyingTin ? (
                        <span className="flex items-center gap-2">
                          <Loader2 className="h-4 w-4 animate-spin" />
                          {t("complaint.tin.verifying")}
                        </span>
                      ) : (
                        t("complaint.tin.verify")
                      )}
                    </Button>
                  </div>
                </form>
              </div>
            ) : (
              <div className="space-y-6">
                <div className="text-center">
                  <h2 className="text-2xl font-semibold text-primary-900">
                    {t("registration.etrade.selectLicenseTitle")}
                  </h2>
                  <p className="mt-2 text-sm text-primary-700">
                    {t("registration.etrade.selectLicenseDescription")}
                  </p>
                  {organizationName && (
                    <p className="mt-2 text-sm font-medium text-primary-900">
                      {organizationName}
                    </p>
                  )}
                </div>

                <div className="max-h-[24rem] space-y-3 overflow-y-auto pr-1">
                  {licenseOptions.map((option) => {
                    const isSelected =
                      selectedLicenseNumber === option.licenseNumber;

                    return (
                      <Card
                        key={option.mainGuid}
                        className={`cursor-pointer border-2 p-4 transition-all ${
                          isSelected
                            ? "border-primary-500 bg-primary-50 ring-2 ring-primary-200"
                            : "border-primary-200 hover:border-primary-300 bg-white"
                        }`}
                        onClick={() =>
                          setSelectedLicenseNumber(option.licenseNumber)
                        }>
                        <div className="space-y-2 text-left">
                          <p className="font-semibold text-primary-900">
                            {option.tradeName}
                          </p>
                          <p className="text-sm text-primary-700">
                            <span className="font-medium">
                              {t("registration.etrade.licenseNumber")}:
                            </span>{" "}
                            <span className="font-mono">
                              {option.licenseNumber}
                            </span>
                          </p>
                          {option.activities.length > 0 && (
                            <p className="text-sm text-primary-600">
                              <span className="font-medium">
                                {t("registration.etrade.activity")}:
                              </span>{" "}
                              {option.activities.join("; ")}
                            </p>
                          )}
                        </div>
                      </Card>
                    );
                  })}
                </div>

                <div className="flex justify-center gap-4">
                  <Button
                    variant="outline"
                    onClick={() => {
                      setTradeLicenseStep("tin");
                      setSelectedLicenseNumber("");
                      setLicenseOptions([]);
                    }}
                    className="border-primary-400 text-primary-700 hover:bg-primary-100"
                    disabled={isRegistering}>
                    {t("registration.etrade.back")}
                  </Button>
                  <Button
                    onClick={handleLicenseSelectionSubmit}
                    disabled={!selectedLicenseNumber || isRegistering}
                    className="bg-primary-600 hover:bg-primary-700 text-white">
                    {isRegistering ? (
                      <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>
            )
          ) : (
            <VerifyOtp
              licenseNo={tradeLicenseNumber}
              onComplete={onVerifyComplete}
              isEtradeVerification={true}
              isExternalOrg={true}
            />
          ))}
      </div>
    </div>
  );
}
