import { Controller, type UseFormReturn } from "react-hook-form";
import { Select, Text } from "@mantine/core";
import {
  ContractFormInputValues,
  OPERATION_TYPE_OPTIONS,
  type ContractFormValues,
  type OperationType,
} from "./schema";
import { AlertBox, fieldStyles } from "./shared";

type ContractForm = UseFormReturn<
  ContractFormInputValues,
  any,
  ContractFormValues
>;

/**
 * Operation type — a single dropdown. The available options reflect the
 * operations the company is registered for; selecting one switches the active
 * company profile so the rest of the wizard is stamped correctly.
 */
export function Step0OperationType({
  form,
  allowedOperations,
  onSelect,
}: {
  form: ContractForm;
  allowedOperations: OperationType[];
  onSelect?: (op: OperationType) => void;
}) {
  const data = OPERATION_TYPE_OPTIONS.filter((opt) =>
    allowedOperations.includes(opt.value),
  ).map((opt) => ({
    value: opt.value,
    label: opt.label,
    disabled: opt.disabled ?? false,
  }));

  return (
    <div className="space-y-3">
      {allowedOperations.length === 0 && (
        <AlertBox tone="error">
          Your company has no operational profile yet. Complete onboarding to
          register as an importer, exporter, or freight forwarder.
        </AlertBox>
      )}

      <Controller
        name="operationType"
        control={form.control}
        render={({ field, fieldState }) => {
          const selected = OPERATION_TYPE_OPTIONS.find(
            (o) => o.value === field.value,
          );
          return (
            <div>
              <Select
                label="Operation Type *"
                placeholder="Select an operation…"
                data={data}
                value={field.value || null}
                onChange={(v) => {
                  if (!v) return;
                  field.onChange(v);
                  onSelect?.(v as OperationType);
                }}
                onBlur={field.onBlur}
                error={fieldState.error?.message}
                allowDeselect={false}
                radius={10}
                checkIconPosition="right"
                comboboxProps={{ withinPortal: true, shadow: "md", radius: "md" }}
                styles={fieldStyles}
              />
              {selected && (
                <Text fz={12.5} c="#6B7C8E" mt={6}>
                  {selected.description}
                </Text>
              )}
            </div>
          );
        }}
      />

      <Text fz={12} c="#6B7C8E">
        Import and Export are stamped to your matching company profile; their
        documents are attached automatically at submission.
      </Text>
    </div>
  );
}
