import { Box, Group, Loader, Stack, Text } from "@mantine/core";
import { useQuery } from "@tanstack/react-query";
import { CheckCircle2, FileText, FileUp } from "lucide-react";
import { SmartFileInput } from "@edr/ui-common";
import { type UseFormReturn } from "react-hook-form";

import useAuth from "@/hooks/useAuth";
import { api } from "@/services/api";
import {
  operationToProfileType,
  type BookingDocuments,
  type BookingFormInputValues,
  type BookingFormValues,
} from "./schema";
import { StepCard, StepHeader } from "./shared";

type BookingForm = UseFormReturn<
  BookingFormInputValues,
  any,
  BookingFormValues
>;

/** Onboarding document setting code for the company's nationality. */
function documentSettingCode(nationality: string | null | undefined): string {
  return nationality === "foreign"
    ? "company_onboarding_documents_foreign"
    : "company_onboarding_documents_ethiopian";
}

function formatSize(bytes?: number): string {
  if (!bytes) return "";
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

/**
 * Editable documents step. Mirrors the company onboarding documents (TIN,
 * passport, investment/commercial license, national ID, …) and lets the customer
 * attach or replace them FOR THIS BOOKING. Selections are stored on the form's
 * `documents` field and saved against the specific booking on submit — editing
 * here never touches the company profile.
 *
 * The documents already on file from onboarding are shown as a reference so the
 * customer can see what EDR already has; they only need to upload here if they
 * want to override a document for this booking.
 */
export function StepDocuments({ form }: { form: BookingForm }) {
  const auth = useAuth();

  const nationality = auth.company?.company?.nationality as
    | string
    | null
    | undefined;

  const docSettingQuery = useQuery(
    api.fileUploadSettings.getByCode.queryOptions({
      input: { code: documentSettingCode(nationality) },
    }),
  );

  // Documents already on file from onboarding (read-only reference), for the
  // profile this booking's operation resolves to (importer/exporter/forwarder).
  const onboardingDocs = (() => {
    const profiles = auth.company?.company?.companyProfiles ?? [];
    const operationType = form.watch("operationType");
    const targetType = operationType
      ? operationToProfileType(
          operationType,
          profiles.map((p) => p.type),
        )
      : null;
    const active =
      (targetType ? profiles.find((p) => p.type === targetType) : undefined) ??
      profiles[0];
    return active?.licenseFiles ?? [];
  })();

  const documents = (form.watch("documents") ?? {}) as BookingDocuments;

  const setDocuments = (next: Record<string, File | File[] | null>) => {
    form.setValue("documents", next, { shouldDirty: true });
  };

  return (
    <StepCard>
      <StepHeader
        icon={<FileUp size={22} />}
        title="Documents"
        description="Attach the documents for this booking. They default to what you uploaded during onboarding — upload here only to override a document for this specific booking."
      />

      {onboardingDocs.length > 0 && (
        <Stack gap={10} mb="lg">
          <Text fz={13} fw={700} c="#10202F">
            On file from your onboarding
          </Text>
          {onboardingDocs.map((doc, i) => (
            <Group
              key={`${doc.id}-${i}`}
              gap={12}
              align="center"
              wrap="nowrap"
              className="rounded-xl"
              style={{
                border: "1px solid var(--mantine-color-edr-border-0)",
                padding: "12px 16px",
              }}
            >
              <Box
                style={{
                  flexShrink: 0,
                  width: 36,
                  height: 36,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  borderRadius: 10,
                  backgroundColor: "#EAF1FB",
                  color: "#2E5B96",
                }}
              >
                <FileText size={18} />
              </Box>
              <Box style={{ minWidth: 0, flex: 1 }}>
                <Text size="sm" fw={600} truncate>
                  {doc.name}
                </Text>
                {doc.size ? (
                  <Text size="xs" c="dimmed">
                    {formatSize(doc.size)}
                  </Text>
                ) : null}
              </Box>
              <Box
                style={{
                  flexShrink: 0,
                  display: "flex",
                  alignItems: "center",
                  gap: 6,
                  color: "#0A6F4D",
                }}
              >
                <CheckCircle2 size={15} />
                <Text size="xs" fw={600} c="#0A6F4D">
                  On file
                </Text>
              </Box>
            </Group>
          ))}
        </Stack>
      )}

      <Text fz={13} fw={700} c="#10202F" mb="sm">
        Documents for this booking
      </Text>

      {docSettingQuery.isLoading ? (
        <Group justify="center" py="lg">
          <Loader size="sm" color="edr-green" />
        </Group>
      ) : docSettingQuery.data ? (
        <SmartFileInput
          file={docSettingQuery.data}
          value={documents}
          onChange={setDocuments}
        />
      ) : (
        <Text size="sm" c="dimmed">
          No document requirements are configured for your account. The documents
          on file from your onboarding will be attached to this booking
          automatically.
        </Text>
      )}
    </StepCard>
  );
}
