"use client";

import type { FieldErrors, UseFormRegister } from "react-hook-form";

import type { MeetingTypeOption } from "@/services/employee-requests/employee-requests.types";
import {
  FraField,
  FraInput,
  FraInputWithPrefix,
  FraSection,
  FraSelect,
  FraTextarea,
} from "./fra-primitives";

/**
 * Section 3 — the case for the trip. This is the half an approver actually
 * reads, so the justification gets the full width and a prompt rather than a
 * bare "Notes".
 *
 * Meeting types are passed in, never hardcoded. They are admin-managed per
 * company: a company with none of its own is served six defaults, but the moment
 * an admin saves one option only theirs are valid and the submit answers
 * UNKNOWN_MEETING_TYPE for anything else.
 */
/**
 * The five fields this section owns, and the only ones it touches.
 *
 * Generic over the form (LEIS-983) because two screens now collect them: step
 * 4's Request approval, and Employee Checkout for a group that needs none.
 * Typing it to `RequestApprovalValues` outright would have forced the checkout
 * form to carry that form's passport-confirmation field, which it has no
 * business asking for a second time.
 */
export interface BusinessInfoValues {
  client?: string;
  opportunity?: string;
  meetingType: string;
  priority: "NORMAL" | "URGENT";
  justification: string;
  /** Read-only on both screens (LEIS-966) — the server derives it from the
   *  add-ons. Present only so the field can be registered and displayed. */
  additionalCost?: string;
}

export function BusinessInfoSection<TValues extends BusinessInfoValues>({
  register,
  errors,
  meetingTypes,
  meetingTypesLoading,
  meetingTypesFailed,
  onRetryMeetingTypes,
  step = 3,
  additionalCost,
}: {
  register: UseFormRegister<TValues>;
  errors: FieldErrors<TValues>;
  meetingTypes: MeetingTypeOption[];
  meetingTypesLoading: boolean;
  meetingTypesFailed: boolean;
  onRetryMeetingTypes: () => void;
  /** Section number. The overlay is section 3; the 4-step page is section 2. */
  step?: number;
  /**
   * Fixed additional cost, rendered read-only instead of as an input.
   *
   * LEIS-966: on the 4-step flow this field "is pre-filled with the extra bag
   * cost from step 3 and is NOT editable" — the figure an admin approves money
   * against has to be one Amadeus actually quoted, not a number anybody can
   * type. The server enforces the same thing; this just stops the form
   * suggesting otherwise. The overlay (and hotels, later) leaves it editable.
   */
  additionalCost?: { amount: string; note: string };
}) {
  return (
    <FraSection step={step} title="Business information">
      <div className="grid grid-cols-1 gap-x-4 gap-y-3.5 sm:grid-cols-2">
        <FraField
          id="client"
          label="Client"
          error={(errors as FieldErrors<BusinessInfoValues>).client?.message}
        >
          {(p) => (
            <FraInput {...p} {...register("client" as never)} placeholder="e.g. ABC Corporation" />
          )}
        </FraField>

        <FraField
          id="opportunity"
          label="Opportunity"
          error={(errors as FieldErrors<BusinessInfoValues>).opportunity?.message}
        >
          {(p) => (
            <FraInput
              {...p}
              {...register("opportunity" as never)}
              placeholder="e.g. Enterprise partnership"
            />
          )}
        </FraField>

        <FraField
          id="meetingType"
          label="Meeting type"
          required
          error={
            (errors as FieldErrors<BusinessInfoValues>).meetingType?.message ??
            (meetingTypesFailed ? "We could not load the meeting types." : undefined)
          }
        >
          {(p) =>
            meetingTypesFailed ? (
              <button
                type="button"
                onClick={onRetryMeetingTypes}
                className="min-h-[38px] w-full rounded-[var(--fra-radius-sm)] border border-[var(--fra-border-strong)] px-[12px] py-2 text-left text-sm font-medium text-[var(--fra-navy-2)] hover:bg-[var(--fra-hover)]"
              >
                Try loading them again
              </button>
            ) : (
              <FraSelect
                {...p}
                {...register("meetingType" as never)}
                disabled={meetingTypesLoading}
              >
                <option value="">{meetingTypesLoading ? "Loading…" : "Select meeting type"}</option>
                {meetingTypes.map((t) => (
                  <option key={t.label} value={t.label}>
                    {t.label}
                  </option>
                ))}
              </FraSelect>
            )
          }
        </FraField>

        <FraField
          id="priority"
          label="Priority"
          error={(errors as FieldErrors<BusinessInfoValues>).priority?.message}
        >
          {(p) => (
            <FraSelect {...p} {...register("priority" as never)}>
              <option value="NORMAL">Normal</option>
              <option value="URGENT">Urgent — fare may change soon</option>
            </FraSelect>
          )}
        </FraField>

        <FraField
          id="justification"
          label="Business justification"
          required
          error={(errors as FieldErrors<BusinessInfoValues>).justification?.message}
          className="sm:col-span-2"
        >
          {(p) => (
            <FraTextarea
              {...p}
              {...register("justification" as never)}
              rows={3}
              placeholder="Why this trip, and why this flight?"
            />
          )}
        </FraField>

        {additionalCost ? (
          <FraField id="additionalCost" label="Additional cost" hint={additionalCost.note}>
            {(p) => (
              <FraInputWithPrefix
                {...p}
                prefix="$"
                type="text"
                value={additionalCost.amount}
                readOnly
                // Not `disabled`: a disabled control is skipped by the tab
                // order and is announced as unavailable, when the point here
                // is that the value matters and simply is not editable.
                aria-readonly="true"
                tabIndex={-1}
                onChange={() => {}}
              />
            )}
          </FraField>
        ) : (
          <FraField
            id="additionalCost"
            label="Additional cost (bags, seats, transfers)"
            error={(errors as FieldErrors<BusinessInfoValues>).additionalCost?.message}
            hint="Leave empty if there is none."
          >
            {(p) => (
              <FraInputWithPrefix
                {...p}
                {...register("additionalCost" as never)}
                prefix="$"
                type="text"
                inputMode="decimal"
                placeholder="0.00"
              />
            )}
          </FraField>
        )}
      </div>
    </FraSection>
  );
}
