import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
  ArrowDownToLine,
  ArrowUpFromLine,
  Building2,
  Ship,
  Truck,
  Check,
} from "lucide-react";
import useAuth from "@/hooks/useAuth";
import { api } from "@/services/api";
import { companiesService } from "@/services/companies.service";
import type { CreateCompanyPayload } from "@/services/companies.service";
import AuthLayout from "@/components/auth/AuthLayout";
import CompanyProfileForm from "./CompanyProfileForm";
import ForwarderForm from "./ForwarderForm";
import DjiboutiAgentForm from "./DjiboutiAgentForm";
import TransporterForm from "./TransporterForm";
import type { OnboardingUserType } from "./types";

const USER_TYPE_CARDS: {
  id: OnboardingUserType;
  label: string;
  description: string;
  icon: React.ReactNode;
}[] = [
    {
      id: "importer",
      label: "Importer",
      description: "Import goods into Ethiopia via the railway corridor.",
      icon: <ArrowDownToLine className="size-6" />,
    },
    {
      id: "exporter",
      label: "Exporter",
      description: "Export goods from Ethiopia via rail.",
      icon: <ArrowUpFromLine className="size-6" />,
    },
    {
      id: "freight-forwarder-et",
      label: "Freight Forwarder (Ethiopia)",
      description: "Ethiopian freight forwarding company handling client cargo.",
      icon: <Building2 className="size-6" />,
    },
    {
      id: "freight-forwarder-dj",
      label: "FF Agent (Djibouti)",
      description: "Djibouti-based agent coordinating cross-border logistics.",
      icon: <Ship className="size-6" />,
    },
    {
      id: "transporter",
      label: "Transporter",
      description: "Trucking company providing first/last-mile services.",
      icon: <Truck className="size-6" />,
    },
  ];

const USER_TYPE_LEFT_MAP: Record<
  OnboardingUserType,
  {
    badge: string;
    title: string;
    description: string;
  }
> = {
  importer: {
    badge: "Importer Registration",
    title: "Register as an Importer",
    description:
      "Set up your company profile to manage imports, track shipments, and streamline customs clearance across the Ethiopia-Djibouti corridor.",
  },
  exporter: {
    badge: "Exporter Registration",
    title: "Register as an Exporter",
    description:
      "Set up your company profile to manage exports, coordinate outbound logistics, and access rail transport services.",
  },
  "freight-forwarder-et": {
    badge: "Freight Forwarder Registration (Ethiopia)",
    title: "Register Your Forwarding Company",
    description:
      "Complete your company profile and Power of Attorney to handle cargo on behalf of importers and exporters.",
  },
  "freight-forwarder-dj": {
    badge: "FF Agent Registration (Djibouti)",
    title: "Register as a Djibouti Agent",
    description:
      "Register your company details and representative information to coordinate cross-border freight operations.",
  },
  transporter: {
    badge: "Transporter Registration",
    title: "Register Your Transport Services",
    description:
      "Provide your vehicle and fleet details to offer first-mile and last-mile trucking services integrated with rail.",
  },
};

const PREFLIGHT_LEFT = {
  badge: "Get Started",
  title: "Choose your account type",
  description:
    "Select the profile that best matches your role in the logistics chain. Each account type provides a tailored onboarding experience.",
  features: [
    "Importers & Exporters",
    "Freight Forwarders (Ethiopia & Djibouti)",
    "Transporters & Fleet Operators",
  ],
  stats: {
    label: "Active Customers",
    value: "500+",
    footer: "And growing",
    progress: "w-[95%]",
  },
};

const DOCUMENT_SETTING_CODE_MAP: Record<OnboardingUserType, string> = {
  importer: "company_onboarding_documents_customer",
  exporter: "company_onboarding_documents_customer",
  "freight-forwarder-et": "company_onboarding_documents_forwarder",
  "freight-forwarder-dj": "company_onboarding_documents_forwarder_dj",
  transporter: "company_onboarding_documents_transporter",
};

export default function OnboardingPage() {
  const queryClient = useQueryClient();
  const { user } = useAuth();
  const [userType, setUserType] = useState<OnboardingUserType | null>(null);
  const [documentFiles, setDocumentFiles] = useState<
    Record<string, File | File[] | null>
  >({});

  const COMPANY_TYPE_MAP: Record<OnboardingUserType, string> = {
    importer: "customer",
    exporter: "customer",
    "freight-forwarder-et": "forwarder",
    "freight-forwarder-dj": "forwarder",
    transporter: "transporter",
  };

  const createCompanyMutation = useMutation({
    mutationFn: (payload: CreateCompanyPayload) =>
      api.companies.create.call(payload),
    onSuccess: async (data) => {
      const hasFiles = Object.values(documentFiles).some(
        (f) => f !== null && (Array.isArray(f) ? f.length > 0 : true),
      );
      if (hasFiles) {
        await companiesService.uploadDocuments(data.company.id, documentFiles);
      }
      await queryClient.invalidateQueries({
        queryKey: api.companies.getInfo.queryKey(),
      });
    },
  });

  if (!user) return null;

  const handleSubmit = (payload: CreateCompanyPayload) => {
    const enriched: CreateCompanyPayload = {
      ...payload,
      companyType: COMPANY_TYPE_MAP[userType!],
    };
    createCompanyMutation.mutate(enriched);
  };

  const handleSelectType = (type: OnboardingUserType) => {
    setUserType(type);
  };

  const handleBack = () => {
    setUserType(null);
  };

  // Preflight: user type selection
  if (!userType) {
    return (
      <AuthLayout left={PREFLIGHT_LEFT}>
        <div className="space-y-6">
          <div>
            <h2 className="text-xl font-bold tracking-tight">
              Select Account Type
            </h2>
            <p className="mt-1 text-sm text-muted-foreground">
              Choose the account type that fits your role.
            </p>
          </div>

          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
            {USER_TYPE_CARDS.map((card) => (
              <button
                key={card.id}
                type="button"
                onClick={() => handleSelectType(card.id)}
                className="group relative flex flex-col items-start gap-3 rounded-xl border-2 border-border bg-card p-4 text-left transition-all hover:border-primary hover:bg-primary/[0.03] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                <div className="flex size-10 items-center justify-center rounded-lg bg-primary/10 text-primary transition-colors group-hover:bg-primary group-hover:text-primary-foreground">
                  {card.icon}
                </div>
                <div>
                  <p className="font-semibold text-foreground">{card.label}</p>
                  <p className="mt-0.5 text-xs text-muted-foreground leading-relaxed">
                    {card.description}
                  </p>
                </div>
                <span className="absolute right-3 top-3 flex size-5 items-center justify-center rounded-full border-2 border-border text-transparent transition-all group-hover:border-primary group-hover:text-primary">
                  <Check className="size-3" />
                </span>
              </button>
            ))}
          </div>
        </div>
      </AuthLayout>
    );
  }

  // Render the appropriate form based on user type
  const leftConfig = USER_TYPE_LEFT_MAP[userType];
  const leftProps = {
    ...leftConfig,
    features:
      userType === "transporter"
        ? [
          "Vehicle & fleet registration",
          "TIN & FAN verification",
          "First-mile / Last-mile eligibility",
        ]
        : userType === "freight-forwarder-dj"
          ? [
            "Company details",
            "Representative information",
            "Cross-border operations",
          ]
          : [
            "Company registration details",
            "Contact and management personnel",
            "Power of Attorney (optional)",
          ],
    stats: {
      label: "Active Customers",
      value: "500+",
      footer: "And growing",
      progress: "w-[95%]",
    },
  };

  return (
    <AuthLayout left={leftProps}>
      {userType === "transporter" ? (
        <TransporterForm
          documentSettingCode={DOCUMENT_SETTING_CODE_MAP[userType]}
          documentFiles={documentFiles}
          onDocumentFilesChange={setDocumentFiles}
          user={user}
          onSubmit={handleSubmit}
          isPending={createCompanyMutation.isPending}
          onBack={handleBack}
        />
      ) : userType === "freight-forwarder-dj" ? (
        <DjiboutiAgentForm
          documentSettingCode={DOCUMENT_SETTING_CODE_MAP[userType]}
          documentFiles={documentFiles}
          onDocumentFilesChange={setDocumentFiles}
          user={user}
          onSubmit={handleSubmit}
          isPending={createCompanyMutation.isPending}
          onBack={handleBack}
        />
      ) : userType === "freight-forwarder-et" ? (
        <ForwarderForm
          documentSettingCode={DOCUMENT_SETTING_CODE_MAP[userType]}
          documentFiles={documentFiles}
          onDocumentFilesChange={setDocumentFiles}
          user={user}
          onSubmit={handleSubmit}
          isPending={createCompanyMutation.isPending}
          onBack={handleBack}
        />
      ) : (
        <CompanyProfileForm
          documentSettingCode={DOCUMENT_SETTING_CODE_MAP[userType]}
          documentFiles={documentFiles}
          onDocumentFilesChange={setDocumentFiles}
          user={user}
          onSubmit={handleSubmit}
          isPending={createCompanyMutation.isPending}
          onBack={handleBack}
        />
      )}
    </AuthLayout>
  );
}
