import { Divider, Grid, Stack, Text, TextInput } from '@mantine/core';
import {
  BLOOD_TYPE_OPTIONS,
  DEPARTMENT_OPTIONS,
  EYE_COLOR_OPTIONS,
  GENDER_OPTIONS,
  HAIR_COLOR_OPTIONS,
  MARITAL_STATUS_OPTIONS,
  RANK_TIER_OPTIONS,
  isEthiopianNationality,
  useGetActiveDepartmentsQuery,
  useLocalized,
} from '@ema-platform/api';
import {
  DateField,
  LocationField,
  NationalityField,
  NumberField,
  SelectField,
  TextField,
  type StepProps,
} from './fields';

function SectionTitle({ title, description }: { title: string; description?: string }) {
  return (
    <div>
      <Text fw={600} fz="sm" tt="uppercase" c="gray.6">
        {title}
      </Text>
      {description && (
        <Text size="sm" c="dimmed" mt={2}>
          {description}
        </Text>
      )}
    </div>
  );
}

/**
 * Step 1 — Identity Details.
 *
 * Email and phone are account credentials: shown, never edited here. The
 * rest is prefilled from the profile and editable — what is entered becomes
 * the registered identity once a reviewer approves.
 */
export function IdentityDetailsStep(
  p: StepProps & { account: { email?: string; phoneNumber?: string } },
) {
  const ethiopian = isEthiopianNationality(p.form.nationality);
  return (
    <Stack gap="lg">
      <SectionTitle title="Contact Details" />
      <Grid>
        <Grid.Col span={{ base: 12, md: 6 }}>
          <TextInput label="Account Email" value={p.account.email ?? ''} disabled />
        </Grid.Col>
        <Grid.Col span={{ base: 12, md: 6 }}>
          <TextInput label="Account Phone Number" value={p.account.phoneNumber ?? ''} disabled />
        </Grid.Col>
      </Grid>
      <Divider />
      <SectionTitle
        title="Identity Details"
        description="Prefilled from your profile where we have it. Check each field and correct anything that is wrong — what you enter here becomes your registered identity."
      />
      <Grid>
        <TextField {...p} name="firstName" label="First Name" required maxLength={128} />
        <TextField {...p} name="middleName" label="Middle Name" maxLength={128} />
        <TextField {...p} name="lastName" label="Last Name" required maxLength={128} />
        <SelectField {...p} name="gender" label="Gender" required options={GENDER_OPTIONS} />
        <DateField {...p} name="dateOfBirth" label="Date of Birth" required />
        <SelectField {...p} name="maritalStatus" label="Marital Status" required options={MARITAL_STATUS_OPTIONS} />
        <NationalityField {...p} name="nationality" label="Nationality" required />
        {ethiopian ? (
          <TextField {...p} name="nationalIdNumber" label="National ID (Fayda) Number" required maxLength={64} />
        ) : (
          <TextField
            {...p}
            name="passportNumber"
            label="Passport Number"
            required
            maxLength={32}
            description="Required for non-Ethiopian applicants in place of a National ID."
          />
        )}
      </Grid>
    </Stack>
  );
}

/**
 * Step 2 — Identity, Address and Physical Characteristics.
 *
 * The department list is backoffice-managed (see the Ranks & Departments
 * configuration tab), so this fetches the live set rather than a fixed
 * three — falling back to it only until the query resolves, so the field
 * is never an empty flash.
 */
export function ApplicantDetailsStep(p: StepProps) {
  const localized = useLocalized();
  const { data: departments } = useGetActiveDepartmentsQuery();
  const departmentOptions =
    departments?.map((d) => ({ value: d.code, label: localized(d.name) })) ??
    DEPARTMENT_OPTIONS;
  // Non-Ethiopians already declare their passport number as their primary ID
  // on the Identity step — asking again here would just duplicate the field.
  const ethiopian = isEthiopianNationality(p.form.nationality);

  return (
    <Stack gap="lg">
      <SectionTitle title="Identity" />
      <Grid>
        <TextField {...p} name="placeOfBirth" label="Place of Birth" required maxLength={128} />
        {ethiopian && (
          <TextField
            {...p}
            name="passportNumber"
            label="Passport Number"
            maxLength={32}
            description="Required later for international sea service; optional at registration."
          />
        )}
        {p.form.passportNumber && (
          <DateField {...p} name="passportExpiry" label="Passport Expiry Date" />
        )}
        <SelectField
          {...p}
          name="department"
          label="Department"
          required
          options={departmentOptions}
          description="The STCW department you serve in. Determines which certificates, examinations and services apply to you."
        />
        <SelectField
          {...p}
          name="tier"
          label="Certificate Limitation"
          required
          options={RANK_TIER_OPTIONS}
          description={
            p.form.department === 'ENGINE'
              ? 'Above covers ships of 3000 kW propulsion power or more; Below covers 750–3000 kW. Every Certificate of Competency you apply for is issued under this limit.'
              : 'Above covers ships of 3000 gross tonnage or more; Below covers 500–3000 GT. Every Certificate of Competency you apply for is issued under this limit.'
          }
        />
      </Grid>

      <Divider />
      <SectionTitle title="Address" />
      <Grid>
        <LocationField
          {...p}
          name="locationId"
          label="Location"
          required
          description="City / sub-city selected from the location picker."
        />
        <TextField {...p} name="permanentAddress" label="Permanent Address" maxLength={255} />
        <TextField
          {...p}
          name="currentAddress"
          label="Current Address"
          maxLength={255}
          description="Where you currently live, if different from the permanent address."
        />
      </Grid>

      <Divider />
      <SectionTitle
        title="Physical Characteristics"
        description="Identifying details printed in your Seaman Book."
      />
      <Grid>
        <SelectField {...p} name="hairColor" label="Hair Colour" required options={HAIR_COLOR_OPTIONS} />
        <SelectField {...p} name="eyeColor" label="Eye Colour" required options={EYE_COLOR_OPTIONS} />
        <NumberField {...p} name="heightCm" label="Height (cm)" required description="In centimetres, e.g. 172.5" />
        <NumberField {...p} name="weightKg" label="Weight (kg)" required description="In kilograms, e.g. 68.0" />
        <SelectField
          {...p}
          name="bloodType"
          label="Blood Type"
          options={BLOOD_TYPE_OPTIONS}
          description="Optional. Select Unknown if you have not been tested."
        />
      </Grid>

    </Stack>
  );
}

/**
 * Step 4 — Emergency Contact and Medical Certificate.
 *
 * The medical certificate used to sit at the bottom of Applicant Details,
 * which made that step 17 fields across four sections while this one held
 * three. Both are short, unrelated-to-identity, and copied off a document in
 * hand rather than recalled — so they pair here and the wizard's longest step
 * drops by a third.
 */
export function EmergencyContactStep(p: StepProps) {
  return (
    <Stack gap="lg">
      <SectionTitle title="Emergency Contact" description="The person EMA contacts in an emergency." />
      <Grid>
        <TextField {...p} name="emergencyContactName" label="Full Name" maxLength={255} />
        <TextField {...p} name="emergencyContactRelationship" label="Relationship" maxLength={64} />
        <TextField {...p} name="emergencyContactPhone" label="Phone Number" maxLength={32} />
      </Grid>

      <Divider />
      <SectionTitle
        title="Medical Certificate"
        description="Details from your STCW medical fitness certificate. The expiry date is calculated from the issue date."
      />
      <Grid>
        <TextField {...p} name="medicalCertificateNumber" label="Certificate Number" required maxLength={64} />
        <TextField {...p} name="medicalIssuerName" label="Issuing Clinic or Practitioner" required maxLength={255} />
        <DateField
          {...p}
          name="medicalIssueDate"
          label="Issue Date"
          required
          // Bounded here rather than only at submit: the calendar is the one
          // place the applicant can see why a day is refused, and the server's
          // rejection otherwise only surfaces five steps later.
          maxDate={new Date()}
          description="Cannot be a future date. Validity is calculated from this: two years, or one year if you are under 18."
        />
      </Grid>
    </Stack>
  );
}
