import { Controller, type UseFormReturn } from "react-hook-form";
import { Field, FieldError, SmartFileInput } from "@edr/ui-common";
import {
  BOOKING_DOCS_SETTING,
  REQUIRED_DOC_KEYS,
  type BookingFormValues,
} from "./schema";
import { getUploadedRequiredCount, StepHeader } from "./shared";

type BookingForm = UseFormReturn<BookingFormValues>;

export function Step7Documents({ form }: { form: BookingForm }) {
  const documents = form.watch("documents");
  const uploadedRequired = getUploadedRequiredCount(documents);
  const documentErrors = form.formState.errors.documents as
    | Record<string, { message?: string }>
    | undefined;
  const smartFileErrors = Object.fromEntries(
    Object.entries(documentErrors ?? {}).map(([key, value]) => [
      key,
      value?.message ?? "",
    ]),
  );

  return (
    <div className="space-y-6">
      <StepHeader
        title="Compliance Documents"
        description="Upload your company's legal credentials for EDR contract eligibility verification (US-04)."
      />

      <div className="flex items-center gap-3 rounded-xl border border-border bg-muted/30 px-4 py-3">
        <div
          className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-bold ${uploadedRequired === REQUIRED_DOC_KEYS.length
              ? "bg-emerald-100 text-emerald-700"
              : "bg-primary/10 text-primary"
            }`}
        >
          {uploadedRequired}/{REQUIRED_DOC_KEYS.length}
        </div>
        <p className="text-sm text-muted-foreground">
          {uploadedRequired < REQUIRED_DOC_KEYS.length
            ? `${REQUIRED_DOC_KEYS.length - uploadedRequired} mandatory document(s) still needed.`
            : "All mandatory documents uploaded. Power of Attorney is optional."}
        </p>
      </div>

      <Controller
        name="documents"
        control={form.control}
        render={({ field, fieldState }) => (
          <Field data-invalid={fieldState.invalid}>
            <SmartFileInput
              file={BOOKING_DOCS_SETTING}
              value={field.value}
              onChange={(value) => field.onChange(value)}
              errors={smartFileErrors}
            />
            <FieldError errors={[fieldState.error]} />
          </Field>
        )}
      />
    </div>
  );
}
