"use client"

import * as React from "react"
import Image from "next/image"
import type { DateRange } from "react-day-picker"
import Select from "react-select"
import { CalendarDays, Loader2, Upload, CheckCircle2, AlertCircle, Download } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Checkbox } from "@/components/ui/checkbox"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Select as LanguageSelect, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { useGetHierarchyTreeQuery, useLazyCheckNimitSevakPhoneExistsQuery, useSubmitNimitSevakMutation } from "@/services/api/formApi"
import {
  createEmptyNimitSevakSevaSelection,
  getNimitSevakStateOptions,
  getNimitSevakSevaOption,
  NIMIT_SEVAK_LANGUAGE_OPTIONS,
  NIMIT_SEVAK_SEVA_OPTIONS,
  type NimitSevakSevaSelection,
  NIMIT_SEVAK_VEHICLE_VALUES,
} from "@/constants/nimit-sevak"
import { messages, toBackendLanguage, type AppLanguage, type TranslationKey } from "@/lib/i18n"
import { cn } from "@/lib/utils"

type Option = {
  value: string
  label: string
}

type FormState = {
  firstName: string
  middleName: string
  lastName: string
  houseNo: string
  societyName: string
  locality: string
  landmark: string
  city: string
  state: string
  pincode: string
  country: string
  aadharCardNo: string
  mobileNo: string
  occupation: string
  age: string
  gender: string
  pradeshId: string
  mandalName: string
  referencePersonName: string
  referencePersonPhoneNo: string
  sevaAvailableFrom: string
  sevaAvailableTo: string
  vehicleAvailableFrom: string
  vehicleAvailableTo: string
  nightShiftAvailable: boolean
}

type ReceiptRow = {
  label: string
  value: string
}

type ReceiptSection = {
  title: string
  rows: ReceiptRow[]
}

type SubmittedReceipt = {
  receiptId: string
  receiptUrl: string | null
  submittedAt: string
  badge: string
  title: string
  subtitle: string
  footerMessage: string
  receiptNumberLabel: string
  submittedOnLabel: string
  sections: ReceiptSection[]
}

const SEVA_DATE_MIN = "2026-10-01"
const SEVA_DATE_MAX = "2027-02-28"
const SEVA_DATE_MIN_VALUE = new Date(2026, 9, 1)
const SEVA_DATE_MAX_VALUE = new Date(2027, 1, 28)

const LANGUAGE_TO_LOCALE: Record<AppLanguage, string> = {
  gu: "gu-IN",
  hi: "hi-IN",
  en: "en-IN",
}

const selectClassNames = {
  control: (state: { isFocused: boolean }) =>
    cn(
      "min-h-11 rounded-md border border-input bg-background px-1 shadow-xs transition",
      state.isFocused ? "border-ring ring-3 ring-ring/20" : ""
    ),
  valueContainer: () => "gap-1 py-0.5",
  placeholder: () => "text-muted-foreground",
  menu: () => "overflow-hidden rounded-md border border-border bg-popover text-popover-foreground shadow-lg",
  option: (state: { isFocused: boolean; isSelected: boolean }) =>
    cn(
      "cursor-pointer px-3 py-2 text-sm",
      state.isSelected && "bg-primary text-primary-foreground",
      !state.isSelected && state.isFocused && "bg-accent text-accent-foreground"
    ),
  multiValue: () => "m-1 inline-flex items-center rounded bg-accent",
  multiValueLabel: () => "px-2 py-1 text-accent-foreground",
  multiValueRemove: () => "rounded-r px-1.5 text-accent-foreground hover:bg-accent/80 hover:text-accent-foreground",
}

const parseInputDate = (value: string) => {
  if (!value) return undefined
  const parsed = new Date(`${value}T00:00:00`)
  return Number.isNaN(parsed.getTime()) ? undefined : parsed
}

const formatDisplayDate = (date: Date, language: AppLanguage) =>
  new Intl.DateTimeFormat(LANGUAGE_TO_LOCALE[language], {
    day: "numeric",
    month: "short",
    year: "numeric",
  }).format(date)

const toInputDateValue = (date: Date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, "0")
  const day = String(date.getDate()).padStart(2, "0")
  return `${year}-${month}-${day}`
}

const isTenDigitPhone = (value: string) => value.replace(/\D/g, "").length === 10

const initialState: FormState = {
  firstName: "",
  middleName: "",
  lastName: "",
  houseNo: "",
  societyName: "",
  locality: "",
  landmark: "",
  city: "",
  state: "",
  pincode: "",
  country: "India",
  aadharCardNo: "",
  mobileNo: "",
  occupation: "",
  age: "",
  gender: "MALE",
  pradeshId: "",
  mandalName: "",
  referencePersonName: "",
  referencePersonPhoneNo: "",
  sevaAvailableFrom: "",
  sevaAvailableTo: "",
  vehicleAvailableFrom: "",
  vehicleAvailableTo: "",
  nightShiftAvailable: false,
}

type ConditionsModalProps = {
  open: boolean
  title: string
  intro: string
  points: string[]
  acceptanceLabel: string
  accepted: boolean
  acceptanceError: string
  errorMessage: string
  isSubmitting: boolean
  cancelLabel: string
  confirmLabel: string
  onAcceptedChange: (checked: boolean) => void
  onCancel: () => void
  onConfirm: () => void
}

export function NimitSevakForm() {
  const [language, setLanguage] = React.useState<AppLanguage>("gu")
  const localize = React.useCallback(
    (gu: string, en: string, hi = en) => {
      if (language === "gu") return gu
      if (language === "hi") return hi
      return en
    },
    [language],
  )
  const t = React.useCallback(
    (key: TranslationKey, fallback?: string) => {
      const localized = (messages[language] as Record<string, string> | undefined)?.[key]
      if (localized) return localized

      const english = (messages.en as Record<string, string>)[key]
      if (english) return english

      return fallback || key
    },
    [language]
  )

  const copy = {
    badge: t("nimitSevak.badge"),
    title: t("nimitSevak.title"),
    subtitle: t("nimitSevak.subtitle"),
    language: t("common.language"),
    next: t("nimitSevak.next"),
    submit: t("nimitSevak.submit"),
    submitting: t("nimitSevak.submitting"),
    submitAnother: t("nimitSevak.submitAnother"),
    required: t("nimitSevak.required"),
    personalInfo: t("nimitSevak.personalInfo"),
    sevaInfo: t("nimitSevak.sevaInfo"),
    vehicleInfo: t("nimitSevak.vehicleInfo"),
    photoInfo: t("nimitSevak.photoInfo"),
    photoInfoHint: t("nimitSevak.photoInfoHint"),
    name: t("nimitSevak.name"),
    firstName: t("nimitSevak.firstName" as never, localize("નામ", "First Name", "नाम")),
    middleName: t("nimitSevak.middleName" as never, localize("પિતાનું નામ", "Middle Name", "पिता का नाम")),
    lastName: t("nimitSevak.lastName" as never, localize("અટક", "Last Name", "उपनाम")),
    address: t("nimitSevak.address"),
    houseNo: t("nimitSevak.houseNo" as never, localize("ઘર નં.", "House No.", "घर नं.")),
    societyName: t("nimitSevak.societyName" as never, localize("સોસાયટીનું નામ", "Society Name", "सोसायटी का नाम")),
    locality: t("nimitSevak.locality" as never, localize("વિસ્તાર / લોકાલિટી", "Locality", "इलाका / लोकैलिटी")),
    landmark: t("nimitSevak.landmark" as never, localize("લેન્ડમાર્ક", "Landmark", "लैंडमार्क")),
    city: t("nimitSevak.city" as never, localize("શહેર", "City", "शहर")),
    state: t("nimitSevak.state" as never, localize("રાજ્ય", "State", "राज्य")),
    selectState: t("nimitSevak.selectState" as never, localize("રાજ્ય પસંદ કરો", "Select State", "राज्य चुनें")),
    pincode: t("nimitSevak.pincode" as never, localize("પિન કોડ", "Pin Code", "पिन कोड")),
    country: t("nimitSevak.country" as never, localize("દેશ", "Country", "देश")),
    aadharCardNo: t("nimitSevak.aadharCardNo"),
    mobileNo: t("nimitSevak.mobileNo"),
    occupation: t("nimitSevak.occupation"),
    age: t("nimitSevak.age"),
    gender: t("nimitSevak.gender"),
    pradesh: t("nimitSevak.pradesh"),
    mandal: t("nimitSevak.mandal"),
    enterMandal: t("nimitSevak.enterMandal"),
    selectMandal: t("nimitSevak.selectMandal" as never, localize("મંડળ પસંદ કરો", "Select Mandal", "मंडल चुनें")),
    referencePersonName: t("nimitSevak.referencePersonName"),
    referencePersonPhoneNo: t("nimitSevak.referencePersonPhoneNo"),
    availableSevas: t("nimitSevak.availableSevas"),
    selectSevas: t("nimitSevak.selectSevas"),
    subSevas: t("nimitSevak.subSevas" as never, localize("ઉપ સેવા", "Sub Sevas", "उप सेवा")),
    selectSubSevas: t("nimitSevak.selectSubSevas" as never, localize("ઉપ સેવા પસંદ કરો", "Select sub sevas", "उप सेवा चुनें")),
    pageLink: t("nimitSevak.pageLink" as never, localize("પેજ લિંક", "Page Link", "पेज लिंक")),
    otherSevaDetails: t("nimitSevak.otherSevaDetails"),
    otherSevaDetailsPlaceholder: t("nimitSevak.otherSevaDetailsPlaceholder" as never, t("nimitSevak.otherSevaDetails")),
    sevaAvailableDates: t("nimitSevak.sevaAvailableDates"),
    dateRangePlaceholder: t("nimitSevak.dateRangePlaceholder"),
    dateFrom: t("nimitSevak.dateFrom"),
    dateTo: t("nimitSevak.dateTo"),
    nightShiftAvailable: t("nimitSevak.nightShiftAvailable"),
    drivableVehicles: t("nimitSevak.drivableVehicles"),
    availableVehicles: t("nimitSevak.availableVehicles"),
    vehicleAvailableDates: t("nimitSevak.vehicleAvailableDates"),
    profilePhoto: t("nimitSevak.profilePhoto"),
    profilePhotoPrompt: t("nimitSevak.profilePhotoPrompt"),
    profilePhotoHint: t("nimitSevak.profilePhotoHint"),
    aadharCardImage: t("nimitSevak.aadharCardImage"),
    aadharCardPrompt: t("nimitSevak.aadharCardPrompt"),
    aadharCardImageHint: t("nimitSevak.aadharCardImageHint"),
    selectPradesh: t("nimitSevak.selectPradesh"),
    selectVehicles: t("nimitSevak.selectVehicles"),
    noOptions: t("nimitSevak.noOptions"),
    invalidPincode: t("nimitSevak.invalidPincode" as never, localize("માન્ય 6 અંકનો પિન કોડ દાખલ કરો", "Enter a valid 6-digit pincode", "मान्य 6 अंकों का पिन कोड दर्ज करें")),
    genderMale: t("registration.gender.male"),
    genderFemale: t("registration.gender.female"),
    genderOther: t("registration.gender.other"),
    thankYouTitle: t("nimitSevak.thankYouTitle"),
    thankYouMessage: t("nimitSevak.thankYouMessage"),
    receiptNumber: t("nimitSevak.receiptNumber" as never),
    receiptSubmittedOn: t("nimitSevak.receiptSubmittedOn" as never),
    downloadReceipt: t("nimitSevak.downloadReceipt" as never),
    hierarchyLoading: t("nimitSevak.hierarchyLoading"),
    hierarchyError: t("nimitSevak.hierarchyError"),
    selectSevaError: t("nimitSevak.selectSevaError"),
    selectPradeshError: t("nimitSevak.selectPradeshError"),
    selectDateRangeError: t("nimitSevak.selectDateRangeError"),
    vehicleDateRequiredError: t("nimitSevak.vehicleDateRequiredError" as never, localize("વાહન સેવા આપવી હોય તો વાહન સેવા તારીખ પસંદ કરવી જરૂરી છે.", "Vehicle availability dates are required when vehicle seva is offered.", "वाहन सेवा देनी हो तो वाहन सेवा तिथि चुनना जरूरी है।")),
    vehicleDateIncompleteError: t("nimitSevak.vehicleDateIncompleteError" as never, localize("વાહન સેવા માટે શરૂઆત અને અંતિમ બંને તારીખ પસંદ કરો.", "Vehicle availability requires both from and to dates.", "वाहन सेवा के लिए शुरुआत और अंत, दोनों तारीखें चुनें।")),
    vehicleDateInvalidError: t("nimitSevak.vehicleDateInvalidError" as never, localize("વાહન સેવા તારીખો માન્ય નથી.", "Vehicle availability dates are invalid.", "वाहन सेवा की तिथियाँ मान्य नहीं हैं।")),
    profilePhotoError: t("nimitSevak.profilePhotoError"),
    aadharCardImageError: t("nimitSevak.aadharCardImageError"),
    submitFailed: t("nimitSevak.submitFailed"),
    invalidPhone: t("registration.toast.enterValidPhone" as never, "Enter a valid 10-digit phone number"),
    phoneAlreadyTaken: t("nimitSevak.phoneAlreadyTaken" as never, localize("આ મોબાઇલ નંબર પહેલેથી ઉપયોગમાં છે.", "Phone number already taken.", "यह मोबाइल नंबर पहले से उपयोग में है।")),
    phoneAvailable: t("nimitSevak.phoneAvailable" as never, localize("મોબાઇલ નંબર ઉપલબ્ધ છે.", "Phone number is available.", "मोबाइल नंबर उपलब्ध है।")),
    phoneVerifyFailed: t("nimitSevak.phoneVerifyFailed" as never, localize("હમણાં મોબાઇલ નંબર ચકાસી શકાયો નથી.", "Unable to verify phone number right now.", "अभी मोबाइल नंबर सत्यापित नहीं हो सका।")),
    requiredNameAddressError: t("nimitSevak.requiredNameAddressError" as never, localize("નામ, સરનામું, વ્યવસાય અને રેફરન્સ વ્યક્તિની તમામ જરૂરી વિગતો ભરો.", "Fill all required name, address, occupation, and reference person details.", "नाम, पता, व्यवसाय और संदर्भ व्यक्ति की सभी जरूरी जानकारी भरें।")),
    invalidAadharCardNo: t("nimitSevak.invalidAadharCardNo" as never, localize("માન્ય 12 અંકનો આધાર કાર્ડ નંબર દાખલ કરો.", "Enter a valid 12-digit Aadhaar card number.", "मान्य 12 अंकों का आधार कार्ड नंबर दर्ज करें।")),
    invalidAge: t("nimitSevak.invalidAge" as never, localize("માન્ય ઉંમર દાખલ કરો.", "Enter a valid age.", "मान्य आयु दर्ज करें।")),
    invalidGender: t("nimitSevak.invalidGender" as never, localize("માન્ય લિંગ પસંદ કરો.", "Select a valid gender.", "मान्य लिंग चुनें।")),
    selectedPradeshNotFound: t("nimitSevak.selectedPradeshNotFound" as never, localize("પસંદ કરેલ પ્રદેશ મળ્યો નથી. કૃપા કરીને ફરી પસંદ કરો.", "Selected Pradesh was not found. Please choose again.", "चुना गया प्रदेश नहीं मिला। कृपया फिर से चुनें।")),
    subSevaRequiredError: t("nimitSevak.subSevaRequiredError" as never, localize("{seva} માટે ઓછામાં ઓછી એક ઉપ સેવા પસંદ કરો.", "Select at least one sub seva for {seva}.", "{seva} के लिए कम से कम एक उप सेवा चुनें।")),
    sevaDetailsRequiredError: t("nimitSevak.sevaDetailsRequiredError" as never, localize("{seva} માટે વિગત આપવી જરૂરી છે.", "Details are required for {seva}.", "{seva} के लिए विवरण देना जरूरी है।")),
    pageLinkRequiredError: t("nimitSevak.pageLinkRequiredError" as never, localize("{subSeva} માટે પેજ લિંક જરૂરી છે.", "Page link is required for {subSeva}.", "{subSeva} के लिए पेज लिंक जरूरी है।")),
    conditionsTitle: t("nimitSevak.conditionsTitle"),
    conditionsIntro: t("nimitSevak.conditionsIntro"),
    conditionsAcceptLabel: t("nimitSevak.conditionsAcceptLabel"),
    conditionsAcceptError: t("nimitSevak.conditionsAcceptError"),
    conditionsCancel: t("nimitSevak.conditionsCancel"),
    conditionsConfirm: t("nimitSevak.conditionsConfirm"),
    conditionOne: t("nimitSevak.condition.1"),
    conditionTwo: t("nimitSevak.condition.2"),
    conditionThree: t("nimitSevak.condition.3"),
    conditionFour: t("nimitSevak.condition.4"),
    conditionFive: t("nimitSevak.condition.5"),
    conditionSix: t("nimitSevak.condition.6"),
    conditionSeven: t("nimitSevak.condition.7"),
    conditionEight: t("nimitSevak.condition.8" as never),
  }

  const formatTemplate = React.useCallback((template: string, values: Record<string, string>) => {
    return Object.entries(values).reduce((message, [key, value]) => message.replaceAll(`{${key}}`, value), template)
  }, [])

  const getSevaLabel = React.useCallback(
    (option: { label: string; labelKey?: TranslationKey }) => t(option.labelKey || (option.label as TranslationKey), option.label),
    [t]
  )

  const getSubSevaLabel = React.useCallback(
    (subOption: { label: string; labelKey?: TranslationKey }) => t(subOption.labelKey || (subOption.label as TranslationKey), subOption.label),
    [t]
  )
  const { data: hierarchyData, isLoading: hierarchyLoading, isError: hierarchyError } = useGetHierarchyTreeQuery()
  const [checkPhoneExists, { isLoading: isCheckingPhone }] = useLazyCheckNimitSevakPhoneExistsQuery()
  const [submitNimitSevak, { isLoading: isSubmitting }] = useSubmitNimitSevakMutation()
  const [form, setForm] = React.useState<FormState>(initialState)
  const [sevaSelections, setSevaSelections] = React.useState<NimitSevakSevaSelection[]>([])
  const [drivableVehicles, setDrivableVehicles] = React.useState<string[]>([])
  const [availableVehicles, setAvailableVehicles] = React.useState<string[]>([])
  const [profilePhoto, setProfilePhoto] = React.useState<File | null>(null)
  const [aadharCardImage, setAadharCardImage] = React.useState<File | null>(null)
  const [errorMessage, setErrorMessage] = React.useState("")
  const [mobileValidation, setMobileValidation] = React.useState<{
    checked: boolean
    exists: boolean
    message: string
  }>({ checked: false, exists: false, message: "" })
  const [lastCheckedMobile, setLastCheckedMobile] = React.useState("")
  const [isConditionsModalOpen, setIsConditionsModalOpen] = React.useState(false)
  const [isSevaDatePickerOpen, setIsSevaDatePickerOpen] = React.useState(false)
  const [isVehicleDatePickerOpen, setIsVehicleDatePickerOpen] = React.useState(false)
  const [hasAcceptedConditions, setHasAcceptedConditions] = React.useState(false)
  const [conditionsError, setConditionsError] = React.useState("")
  const [submitted, setSubmitted] = React.useState(false)
  const [submittedReceipt, setSubmittedReceipt] = React.useState<SubmittedReceipt | null>(null)

  React.useEffect(() => {
    if (!isConditionsModalOpen) return

    const previousOverflow = document.body.style.overflow
    document.body.style.overflow = "hidden"

    return () => {
      document.body.style.overflow = previousOverflow
    }
  }, [isConditionsModalOpen])

  const pradeshOptions = (hierarchyData?.data || []).map((pradesh) => ({
    value: String(pradesh.pradeshId),
    label: pradesh.pradeshName,
  }))
  const selectedPradesh = (hierarchyData?.data || []).find((pradesh) => String(pradesh.pradeshId) === form.pradeshId) || null
  const mandalOptions = (selectedPradesh?.mandals || []).map((mandal) => ({
    value: mandal.mandalName,
    label: mandal.mandalName,
  }))

  const vehicleOptions = NIMIT_SEVAK_VEHICLE_VALUES.map((value) => ({
    value,
    label: t(`nimitSevak.vehicle.${value}` as never),
  }))
  const localizedStateOptions = getNimitSevakStateOptions(language)

  const selectedDrivableVehicleOptions = vehicleOptions.filter((option) => drivableVehicles.includes(option.value))
  const selectedAvailableVehicleOptions = vehicleOptions.filter((option) => availableVehicles.includes(option.value))
  const selectedSevaCodes = sevaSelections.map((selection) => selection.sevaCode)
  const localizedSevaOptions = NIMIT_SEVAK_SEVA_OPTIONS.map((option) => ({
    value: option.value,
    label: getSevaLabel(option),
  }))
  const selectedSevaOptions = localizedSevaOptions.filter((option) => selectedSevaCodes.includes(option.value))
  const sevaDateRange: DateRange | undefined = {
    from: parseInputDate(form.sevaAvailableFrom),
    to: parseInputDate(form.sevaAvailableTo),
  }
  const vehicleDateRange: DateRange | undefined = {
    from: parseInputDate(form.vehicleAvailableFrom),
    to: parseInputDate(form.vehicleAvailableTo),
  }
  const conditionPoints = [
    copy.conditionOne,
    copy.conditionTwo,
    copy.conditionThree,
    copy.conditionFour,
    copy.conditionFive,
    copy.conditionSix,
    copy.conditionSeven,
    copy.conditionEight,
  ]
  const isMobileInvalid = Boolean(form.mobileNo) && !isTenDigitPhone(form.mobileNo)
  const isReferencePhoneInvalid = Boolean(form.referencePersonPhoneNo) && !isTenDigitPhone(form.referencePersonPhoneNo)

  const verifyMobileNumber = React.useCallback(
    async (normalizedPhone: string) => {
      if (normalizedPhone.length !== 10 || normalizedPhone === lastCheckedMobile) {
        return
      }

      try {
        const result = await checkPhoneExists({ phone: normalizedPhone }).unwrap()

        setMobileValidation({
          checked: true,
          exists: result.exists,
          message: result.exists ? copy.phoneAlreadyTaken : copy.phoneAvailable,
        })
        setLastCheckedMobile(normalizedPhone)
      } catch {
        setMobileValidation({ checked: true, exists: false, message: copy.phoneVerifyFailed })
        setLastCheckedMobile(normalizedPhone)
      }
    },
    [checkPhoneExists, copy.phoneAlreadyTaken, copy.phoneAvailable, copy.phoneVerifyFailed, lastCheckedMobile]
  )

  React.useEffect(() => {
    if (form.mobileNo.length !== 10) return

    const timer = window.setTimeout(() => {
      void verifyMobileNumber(form.mobileNo)
    }, 300)

    return () => window.clearTimeout(timer)
  }, [form.mobileNo, verifyMobileNumber])

  const handleChange = (field: keyof FormState, value: string) => {
    setForm((current) => ({ ...current, [field]: value }))
  }

  const handleMobileChange = (value: string) => {
    setForm((current) => ({ ...current, mobileNo: value }))
    setMobileValidation({ checked: false, exists: false, message: "" })
    setLastCheckedMobile("")
  }

  const handleMobileBlur = async () => {
    const normalizedPhone = form.mobileNo.replace(/\D/g, "").slice(0, 10)

    if (normalizedPhone.length !== 10) {
      setMobileValidation({ checked: false, exists: false, message: "" })
      setLastCheckedMobile("")
      return
    }

    if (normalizedPhone === lastCheckedMobile) {
      return
    }

    await verifyMobileNumber(normalizedPhone)
  }

  const assembleFullName = React.useCallback(
    (value: FormState) => [value.firstName, value.middleName, value.lastName].map((part) => part.trim()).filter(Boolean).join(" ") || "-",
    [],
  )

  const assembleAddress = React.useCallback(
    (value: FormState) =>
      [value.houseNo, value.societyName, value.locality, value.landmark, value.city, value.state, value.pincode, value.country]
        .map((part) => part.trim())
        .filter(Boolean)
        .join(", ") || "-",
    [],
  )

  const handleSevaOptionsChange = (options: readonly Option[]) => {
    const nextCodes = options.map((option) => option.value)

    setSevaSelections((current) => {
      const existingSelections = new Map(current.map((selection) => [selection.sevaCode, selection]))
      return nextCodes.map((sevaCode) => existingSelections.get(sevaCode) || createEmptyNimitSevakSevaSelection(sevaCode))
    })
  }

  const updateSevaSelection = (sevaCode: string, updater: (selection: NimitSevakSevaSelection) => NimitSevakSevaSelection) => {
    setSevaSelections((current) =>
      current.map((selection) => (selection.sevaCode === sevaCode ? updater(selection) : selection)),
    )
  }

  const handleSubSevaOptionsChange = (sevaCode: string, options: readonly Option[]) => {
    const nextSubSevas = options.map((option) => option.value)

    updateSevaSelection(sevaCode, (selection) => {
      const nextPageLinks = Object.fromEntries(
        Object.entries(selection.pageLinks).filter(([subSevaCode]) => nextSubSevas.includes(subSevaCode)),
      )

      return {
        ...selection,
        subSevaCodes: nextSubSevas,
        pageLinks: nextPageLinks,
      }
    })
  }

  const getSevaValidationError = React.useCallback(() => {
    if (!sevaSelections.length) return copy.selectSevaError

    for (const selection of sevaSelections) {
      const option = getNimitSevakSevaOption(selection.sevaCode)
      if (!option) continue

      if (option.subSevas?.length && !selection.subSevaCodes.length) {
        return formatTemplate(copy.subSevaRequiredError, { seva: getSevaLabel(option) })
      }

      if (option.requiresTextInput && !String(selection.customValue || "").trim()) {
        return formatTemplate(copy.sevaDetailsRequiredError, { seva: getSevaLabel(option) })
      }

      for (const subSevaCode of selection.subSevaCodes) {
        const subOption = option.subSevas?.find((entry) => entry.value === subSevaCode)
        if (subOption?.requiresPageLink && !String(selection.pageLinks[subSevaCode] || "").trim()) {
          return formatTemplate(copy.pageLinkRequiredError, { subSeva: getSubSevaLabel(subOption) })
        }
      }
    }

    return ""
  }, [copy.pageLinkRequiredError, copy.selectSevaError, copy.sevaDetailsRequiredError, copy.subSevaRequiredError, formatTemplate, getSevaLabel, getSubSevaLabel, sevaSelections])

  const translateBackendError = React.useCallback(
    (message?: string | null) => {
      const normalized = String(message || "").trim()
      if (!normalized) return copy.submitFailed

      const backendErrorMap: Record<string, string> = {
        "Split name, split address, occupation, mandal, and reference person name are required": copy.requiredNameAddressError,
        "Valid 6-digit pincode is required": copy.invalidPincode,
        "Valid Aadhaar card number is required": copy.invalidAadharCardNo,
        "Valid mobile number is required": copy.invalidPhone,
        "Valid reference person phone number is required": copy.invalidPhone,
        "Valid age is required": copy.invalidAge,
        "Valid gender is required": copy.invalidGender,
        "Pradesh is required": copy.selectPradeshError,
        "Please select at least one seva": copy.selectSevaError,
        "Valid seva availability dates are required": copy.selectDateRangeError,
        "Seva date range must be between 01 Oct 2026 and 28 Feb 2027": copy.selectDateRangeError,
        "Vehicle availability dates are required when vehicle seva is offered": copy.vehicleDateRequiredError,
        "Vehicle availability requires both from and to dates": copy.vehicleDateIncompleteError,
        "Vehicle availability dates are invalid": copy.vehicleDateInvalidError,
        "Profile photo is required": copy.profilePhotoError,
        "Aadhaar card image is required": copy.aadharCardImageError,
        "Selected Pradesh was not found": copy.selectedPradeshNotFound,
      }

      return backendErrorMap[normalized] || normalized
    },
    [
      copy.aadharCardImageError,
      copy.invalidAadharCardNo,
      copy.invalidAge,
      copy.invalidGender,
      copy.invalidPhone,
      copy.invalidPincode,
      copy.profilePhotoError,
      copy.requiredNameAddressError,
      copy.selectDateRangeError,
      copy.selectedPradeshNotFound,
      copy.selectPradeshError,
      copy.selectSevaError,
      copy.submitFailed,
      copy.vehicleDateIncompleteError,
      copy.vehicleDateInvalidError,
      copy.vehicleDateRequiredError,
    ],
  )

  const formatReceiptDateRange = (from?: string, to?: string) => {
    const fromDate = parseInputDate(from || "")
    const toDate = parseInputDate(to || "")

    if (fromDate && toDate) {
      return `${formatDisplayDate(fromDate, language)} - ${formatDisplayDate(toDate, language)}`
    }

    return "-"
  }

  const joinValues = (values: string[]) => (values.length ? values.join(", ") : "-")

  const formatReceiptSevaLabel = React.useCallback(
    (selection: NimitSevakSevaSelection) => {
      const option = getNimitSevakSevaOption(selection.sevaCode)
      const optionLabel = option ? getSevaLabel(option) : selection.sevaCode
      const customValue = String(selection.customValue || "").trim()

      if (selection.sevaCode === "OTHER" && customValue) {
        return `${optionLabel} - ${customValue}`
      }

      return optionLabel
    },
    [getSevaLabel],
  )

  const createSubmittedReceipt = (submission?: {
    receiptNumber: string | null
    receiptUrl: string | null
    receiptGeneratedAt: string | null
  }): SubmittedReceipt => {
    const submittedAtDate = submission?.receiptGeneratedAt ? new Date(submission.receiptGeneratedAt) : new Date()
    const submittedAt = new Intl.DateTimeFormat(LANGUAGE_TO_LOCALE[language], {
      day: "2-digit",
      month: "short",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    }).format(submittedAtDate)

    const pradeshName = pradeshOptions.find((option) => option.value === form.pradeshId)?.label || "-"
    const sevaLabels = sevaSelections.map((selection) => formatReceiptSevaLabel(selection))
    const drivableVehicleLabels = selectedDrivableVehicleOptions.map((option) => option.label)
    const availableVehicleLabels = selectedAvailableVehicleOptions.map((option) => option.label)
    const genderLabel =
      form.gender === "FEMALE"
        ? copy.genderFemale
        : form.gender === "OTHER"
          ? copy.genderOther
          : copy.genderMale
    const receiptId = submission?.receiptNumber || ""

    return {
      receiptId,
      receiptUrl: submission?.receiptUrl || null,
      submittedAt,
      badge: copy.badge,
      title: copy.title,
      subtitle: copy.subtitle,
      footerMessage: copy.thankYouMessage,
      receiptNumberLabel: copy.receiptNumber,
      submittedOnLabel: copy.receiptSubmittedOn,
      sections: [
        {
          title: copy.personalInfo,
          rows: [
            { label: copy.name, value: assembleFullName(form) },
            { label: copy.mobileNo, value: form.mobileNo || "-" },
            { label: copy.aadharCardNo, value: form.aadharCardNo || "-" },
            { label: copy.age, value: form.age || "-" },
            { label: copy.gender, value: genderLabel },
            { label: copy.occupation, value: form.occupation.trim() || "-" },
            { label: copy.pradesh, value: pradeshName },
            { label: copy.mandal, value: form.mandalName.trim() || "-" },
            { label: copy.referencePersonName, value: form.referencePersonName.trim() || "-" },
            { label: copy.referencePersonPhoneNo, value: form.referencePersonPhoneNo || "-" },
            { label: copy.address, value: assembleAddress(form) },
          ],
        },
        {
          title: copy.sevaInfo,
          rows: [
            { label: copy.availableSevas, value: joinValues(sevaLabels) },
            { label: copy.sevaAvailableDates, value: formatReceiptDateRange(form.sevaAvailableFrom, form.sevaAvailableTo) },
            { label: copy.nightShiftAvailable, value: form.nightShiftAvailable ? copy.nightShiftAvailable : "-" },
          ],
        },
        {
          title: copy.vehicleInfo,
          rows: [
            { label: copy.drivableVehicles, value: joinValues(drivableVehicleLabels) },
            { label: copy.availableVehicles, value: joinValues(availableVehicleLabels) },
            { label: copy.vehicleAvailableDates, value: formatReceiptDateRange(form.vehicleAvailableFrom, form.vehicleAvailableTo) },
          ],
        },
      ],
    }
  }

  const handleDownloadReceipt = async () => {
    if (!submittedReceipt?.receiptUrl) return

    try {
      const response = await fetch(submittedReceipt.receiptUrl)
      const blob = await response.blob()
      const url = URL.createObjectURL(blob)
      const link = document.createElement("a")
      link.href = url
      link.download = `nimit-sevak-receipt-${submittedReceipt.receiptId}.pdf`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
    } catch {
      window.open(submittedReceipt.receiptUrl, "_blank", "noopener,noreferrer")
    }
  }

  const resetForm = () => {
    setForm(initialState)
    setSevaSelections([])
    setDrivableVehicles([])
    setAvailableVehicles([])
    setProfilePhoto(null)
    setAadharCardImage(null)
    setErrorMessage("")
    setIsSevaDatePickerOpen(false)
    setIsVehicleDatePickerOpen(false)
  }

  const handleSevaDateRangeChange = (range: DateRange | undefined) => {
    setForm((current) => ({
      ...current,
      sevaAvailableFrom: range?.from ? toInputDateValue(range.from) : "",
      sevaAvailableTo: range?.to ? toInputDateValue(range.to) : "",
    }))
  }

  const handleVehicleDateRangeChange = (range: DateRange | undefined) => {
    setForm((current) => ({
      ...current,
      vehicleAvailableFrom: range?.from ? toInputDateValue(range.from) : "",
      vehicleAvailableTo: range?.to ? toInputDateValue(range.to) : "",
    }))
  }

  const sevaDateRangeLabel =
    sevaDateRange?.from && sevaDateRange?.to
      ? `${formatDisplayDate(sevaDateRange.from, language)} - ${formatDisplayDate(sevaDateRange.to, language)}`
      : copy.dateRangePlaceholder

  const vehicleDateRangeLabel =
    vehicleDateRange?.from && vehicleDateRange?.to
      ? `${formatDisplayDate(vehicleDateRange.from, language)} - ${formatDisplayDate(vehicleDateRange.to, language)}`
      : copy.dateRangePlaceholder

  const validateForm = () => {
    setErrorMessage("")

    const sevaValidationError = getSevaValidationError()
    if (sevaValidationError) {
      setErrorMessage(sevaValidationError)
      return false
    }

    if (!isTenDigitPhone(form.mobileNo) || !isTenDigitPhone(form.referencePersonPhoneNo)) {
      setErrorMessage(copy.invalidPhone)
      return false
    }

    if (mobileValidation.exists) {
      setErrorMessage(mobileValidation.message)
      return false
    }

    if (!form.pradeshId || !form.mandalName.trim()) {
      setErrorMessage(copy.selectPradeshError)
      return false
    }

    if ([form.firstName, form.middleName, form.lastName, form.houseNo, form.societyName, form.locality, form.city, form.state, form.occupation, form.referencePersonName].some((value) => !value.trim())) {
      setErrorMessage(copy.requiredNameAddressError)
      return false
    }

    if (form.pincode.replace(/\D/g, "").length !== 6) {
      setErrorMessage(copy.invalidPincode)
      return false
    }

    if (form.aadharCardNo.replace(/\D/g, "").length !== 12) {
      setErrorMessage(copy.invalidAadharCardNo)
      return false
    }

    const age = Number.parseInt(form.age, 10)
    if (!Number.isInteger(age) || age < 1 || age > 120) {
      setErrorMessage(copy.invalidAge)
      return false
    }

    if (!["MALE", "FEMALE", "OTHER"].includes(form.gender)) {
      setErrorMessage(copy.invalidGender)
      return false
    }

    if (
      !form.sevaAvailableFrom ||
      !form.sevaAvailableTo ||
      form.sevaAvailableFrom > form.sevaAvailableTo ||
      form.sevaAvailableFrom < SEVA_DATE_MIN ||
      form.sevaAvailableTo > SEVA_DATE_MAX
    ) {
      setErrorMessage(copy.selectDateRangeError)
      return false
    }

    if (availableVehicles.length && (!form.vehicleAvailableFrom || !form.vehicleAvailableTo)) {
      setErrorMessage(copy.vehicleDateRequiredError)
      return false
    }

    if ((form.vehicleAvailableFrom && !form.vehicleAvailableTo) || (!form.vehicleAvailableFrom && form.vehicleAvailableTo)) {
      setErrorMessage(copy.vehicleDateIncompleteError)
      return false
    }

    if (form.vehicleAvailableFrom && form.vehicleAvailableTo && form.vehicleAvailableFrom > form.vehicleAvailableTo) {
      setErrorMessage(copy.vehicleDateInvalidError)
      return false
    }

    if (!profilePhoto) {
      setErrorMessage(copy.profilePhotoError)
      return false
    }

    if (!aadharCardImage) {
      setErrorMessage(copy.aadharCardImageError)
      return false
    }

    return true
  }

  const closeConditionsModal = () => {
    if (isSubmitting) return

    setIsConditionsModalOpen(false)
    setHasAcceptedConditions(false)
    setConditionsError("")
  }

  const submitForm = async () => {
    if (!profilePhoto || !aadharCardImage) {
      setErrorMessage(!profilePhoto ? copy.profilePhotoError : copy.aadharCardImageError)
      return
    }

    const payload = new FormData()
    payload.append("firstName", form.firstName.trim())
    payload.append("middleName", form.middleName.trim())
    payload.append("lastName", form.lastName.trim())
    payload.append("houseNo", form.houseNo.trim())
    payload.append("societyName", form.societyName.trim())
    payload.append("locality", form.locality.trim())
    payload.append("landmark", form.landmark.trim())
    payload.append("city", form.city.trim())
    payload.append("state", form.state.trim())
    payload.append("pincode", form.pincode.replace(/\D/g, "").slice(0, 6))
    payload.append("country", form.country.trim())
    payload.append("aadharCardNo", form.aadharCardNo.replace(/\D/g, ""))
    payload.append("mobileNo", form.mobileNo.replace(/\D/g, ""))
    payload.append("occupation", form.occupation.trim())
    payload.append("age", form.age)
    payload.append("gender", form.gender)
    payload.append("pradeshId", form.pradeshId)
    payload.append("mandalName", form.mandalName.trim())
    payload.append("referencePersonName", form.referencePersonName.trim())
    payload.append("referencePersonPhoneNo", form.referencePersonPhoneNo.replace(/\D/g, ""))
    payload.append("selectedSevas", JSON.stringify(selectedSevaCodes))
    payload.append("sevaSelections", JSON.stringify(sevaSelections))
    payload.append("sevaAvailableFrom", form.sevaAvailableFrom)
    payload.append("sevaAvailableTo", form.sevaAvailableTo)
    payload.append("nightShiftAvailable", String(form.nightShiftAvailable))
    payload.append("drivableVehicles", JSON.stringify(drivableVehicles))
    payload.append("availableVehicles", JSON.stringify(availableVehicles))
    payload.append("vehicleAvailableFrom", form.vehicleAvailableFrom)
    payload.append("vehicleAvailableTo", form.vehicleAvailableTo)
    payload.append("preferredLanguage", toBackendLanguage(language))
    payload.append("profilePhoto", profilePhoto)
    payload.append("aadharCardImage", aadharCardImage)

    try {
      const response = await submitNimitSevak(payload).unwrap()
      if (!response.success) {
        setErrorMessage(translateBackendError(response.error))
        return
      }

      setSubmittedReceipt(createSubmittedReceipt(response.data))
      setSubmitted(true)
      setIsConditionsModalOpen(false)
      setHasAcceptedConditions(false)
      setConditionsError("")
      resetForm()
    } catch (error) {
      const fallback = "data" in (error as Record<string, unknown>)
        ? translateBackendError((error as { data?: { error?: string } }).data?.error)
        : copy.submitFailed
      setErrorMessage(fallback)
    }
  }

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()

    if (!validateForm()) return

    setHasAcceptedConditions(false)
    setConditionsError("")
    setIsConditionsModalOpen(true)
  }

  const handleConfirmSubmit = async () => {
    setConditionsError("")

    if (!hasAcceptedConditions) {
      setConditionsError(copy.conditionsAcceptError)
      return
    }

    await submitForm()
  }

  const localizedLanguageOptions = NIMIT_SEVAK_LANGUAGE_OPTIONS.map((option) => ({
    value: option.value,
    label: t(option.label as never),
  }))

  const languageValue = localizedLanguageOptions.find((option) => option.value === language)?.value || "en"

  if (submitted) {
    return (
      <section className="mx-auto flex min-h-screen w-full max-w-4xl items-center px-4 py-10 sm:px-6">
        <Card className="w-full overflow-hidden border-[#f4dcc5] bg-white/95 shadow-[0_24px_80px_rgba(89,29,0,0.12)]">
          <CardContent className="flex flex-col items-center gap-5 px-6 py-12 text-center sm:px-10">
            <div className="rounded-full bg-[#fef0d5] p-4 text-[#9f1d20]">
              <CheckCircle2 className="size-10" />
            </div>
            <Image src="/smruti/2025-03-26 Shikshapatri Logo.png" alt="Shikshapatri logo" width={240} height={170} className="h-auto w-44 sm:w-56" priority />
            <div className="space-y-2">
              <h2 className="text-3xl font-extrabold tracking-tight text-[#7b1017]">{copy.thankYouTitle}</h2>
              <p className="mx-auto max-w-2xl whitespace-pre-line text-base leading-7 text-[#6a5746]">{copy.thankYouMessage}</p>
            </div>
            {submittedReceipt ? (
              <div className="w-full rounded-[1.75rem] border border-[#efcfaf] bg-[linear-gradient(180deg,_#fffdf8_0%,_#fff4e7_100%)] p-5 text-left shadow-[0_20px_80px_rgba(89,29,0,0.10)] sm:p-6">
                <div className="space-y-4">
                  <div className="space-y-2 border-b border-[#efd8bf] pb-4">
                    <div className="inline-flex w-fit rounded-full border border-primary/20 bg-primary/10 px-3 py-1 text-xs font-bold uppercase tracking-[0.24em] text-primary">
                      {submittedReceipt.badge}
                    </div>
                    <h3 className="text-2xl font-black tracking-tight text-[#7b1017]">{submittedReceipt.title}</h3>
                    <p className="whitespace-pre-line text-sm leading-6 text-[#6e5a49]">{submittedReceipt.subtitle}</p>
                  </div>

                  <div className="grid gap-3 md:grid-cols-2">
                    {submittedReceipt.receiptId ? (
                      <div className="rounded-2xl border border-[#f1dfcb] bg-[#fffaf4] px-4 py-3">
                        <div className="text-xs font-bold uppercase tracking-[0.16em] text-[#8b6b4f]">{submittedReceipt.receiptNumberLabel}</div>
                        <div className="mt-1 text-sm font-semibold text-[#4b3727]">{submittedReceipt.receiptId}</div>
                      </div>
                    ) : null}
                    <div className="rounded-2xl border border-[#f1dfcb] bg-[#fffaf4] px-4 py-3">
                      <div className="text-xs font-bold uppercase tracking-[0.16em] text-[#8b6b4f]">{submittedReceipt.submittedOnLabel}</div>
                      <div className="mt-1 text-sm font-semibold text-[#4b3727]">{submittedReceipt.submittedAt}</div>
                    </div>
                  </div>

                  <div className="grid gap-4">
                    {submittedReceipt.sections.map((section) => (
                      <div key={section.title} className="space-y-3">
                        <h4 className="text-lg font-bold text-[#7b1017]">{section.title}</h4>
                        <div className="grid gap-3 md:grid-cols-2">
                          {section.rows.map((row) => (
                            <div key={`${section.title}-${row.label}`} className="rounded-2xl border border-[#f1dfcb] bg-white px-4 py-3">
                              <div className="text-sm text-[#8b6b4f]">{row.label}</div>
                              <div className="mt-1 whitespace-pre-line text-sm font-semibold text-[#4b3727]">{row.value}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                  <div className="whitespace-pre-line rounded-2xl border border-[#f1dfcb] bg-[#fffaf4] px-4 py-4 text-sm leading-7 text-[#6e5a49]">
                    {submittedReceipt.footerMessage}
                  </div>
                </div>
              </div>
            ) : null}
            <div className="flex flex-col gap-3 sm:flex-row">
              {submittedReceipt?.receiptUrl ? (
                <Button type="button" variant="outline" className="border-[#d5b18d] bg-white text-[#74462b] hover:bg-[#fff4e8]" onClick={handleDownloadReceipt}>
                  <Download className="size-4" />
                  {copy.downloadReceipt}
                </Button>
              ) : null}
              <Button type="button" className="bg-[#9f1d20] hover:bg-[#7f1619]" onClick={() => {
                setSubmitted(false)
                setSubmittedReceipt(null)
              }}>
                {copy.submitAnother}
              </Button>
            </div>
          </CardContent>
        </Card>
      </section>
    )
  }

  return (
    <section className="min-h-screen bg-[radial-gradient(circle_at_top,_rgba(252,224,165,0.38),_transparent_36%),linear-gradient(180deg,_#fffaf4_0%,_#fff1df_48%,_#fff8f0_100%)] px-4 py-6 sm:px-6 sm:py-10">
      <div className="mx-auto flex w-full max-w-6xl flex-col gap-6">
        <Card className="overflow-hidden border-[#f1d8bb] bg-white/90 shadow-[0_30px_100px_rgba(95,40,0,0.12)] backdrop-blur">
          <CardContent className="grid gap-8 px-6 py-6 sm:px-8 lg:grid-cols-[1.2fr_0.8fr] lg:items-center">
            <div className="space-y-4">
              <div className="inline-flex w-fit rounded-full border border-primary/20 bg-primary/10 px-3 py-1 text-xs font-bold uppercase tracking-[0.24em] text-primary">
                {copy.badge}
              </div>
              <div className="space-y-3">
                <h1 className="text-3xl font-black tracking-tight text-[#7b1017] sm:text-5xl">{copy.title}</h1>
                <p className="max-w-2xl text-base leading-7 text-muted-foreground sm:text-lg">{copy.subtitle}</p>
              </div>
            </div>
            <div className="flex flex-col items-center gap-4 rounded-[2rem] bg-[linear-gradient(160deg,_#fff9f2_0%,_#ffe1c2_100%)] p-6 shadow-inner">
              <Image src="/smruti/2025-03-26 Shikshapatri Logo.png" alt="Shikshapatri logo" width={360} height={300} className="h-auto w-full max-w-[280px]" priority />
              <div className="w-full max-w-xs space-y-2">
                <Label>{copy.language}</Label>
                <LanguageSelect value={languageValue} onValueChange={(value) => setLanguage(value as AppLanguage)}>
                  <SelectTrigger className="h-11 w-full border-[#e8d3bd] bg-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {localizedLanguageOptions.map((option) => (
                      <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                    ))}
                  </SelectContent>
                </LanguageSelect>
              </div>
            </div>
          </CardContent>
        </Card>

        <form onSubmit={handleSubmit} className="grid gap-6 pb-8">
          <Card className="border-[#f0dcc6] bg-white/95 shadow-[0_16px_60px_rgba(110,57,0,0.08)]">
            <CardHeader>
              <CardTitle className="text-[#7b1017]">{copy.personalInfo}</CardTitle>
              <CardDescription>{copy.required}</CardDescription>
            </CardHeader>
            <CardContent className="grid gap-5 md:grid-cols-2">
              <Field label={copy.firstName}><Input required value={form.firstName} onChange={(event) => handleChange("firstName", event.target.value)} /></Field>
              <Field label={copy.middleName}><Input required value={form.middleName} onChange={(event) => handleChange("middleName", event.target.value)} /></Field>
              <Field label={copy.lastName}><Input required value={form.lastName} onChange={(event) => handleChange("lastName", event.target.value)} /></Field>
              <Field label={copy.mobileNo}>
                <div className="space-y-2">
                  <Input
                    required
                    inputMode="numeric"
                    maxLength={10}
                    value={form.mobileNo}
                    onChange={(event) => handleMobileChange(event.target.value.replace(/\D/g, "").slice(0, 10))}
                    onBlur={handleMobileBlur}
                  />
                  {isMobileInvalid ? (
                    <p className="text-xs text-[#922020]">{copy.invalidPhone}</p>
                  ) : isCheckingPhone ? (
                    <p className="text-xs text-[#8b6b4f]">Checking phone number...</p>
                  ) : mobileValidation.checked && mobileValidation.message ? (
                    <p className={cn("text-xs", mobileValidation.exists ? "text-[#922020]" : "text-emerald-700")}>
                      {mobileValidation.message}
                    </p>
                  ) : null}
                </div>
              </Field>
              <Field label={copy.aadharCardNo}><Input required inputMode="numeric" maxLength={12} value={form.aadharCardNo} onChange={(event) => handleChange("aadharCardNo", event.target.value.replace(/\D/g, "").slice(0, 12))} /></Field>
              <Field label={copy.occupation}><Input required value={form.occupation} onChange={(event) => handleChange("occupation", event.target.value)} /></Field>
              <Field label={copy.age}><Input required type="number" min={1} max={120} value={form.age} onChange={(event) => handleChange("age", event.target.value)} /></Field>
              <Field label={copy.gender}>
                <LanguageSelect value={form.gender} onValueChange={(value) => handleChange("gender", value)}>
                  <SelectTrigger className="h-11 w-full border-[#e8d3bd] bg-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="MALE">{copy.genderMale}</SelectItem>
                    <SelectItem value="FEMALE">{copy.genderFemale}</SelectItem>
                    <SelectItem value="OTHER">{copy.genderOther}</SelectItem>
                  </SelectContent>
                </LanguageSelect>
              </Field>
              <Field label={copy.houseNo}><Input required value={form.houseNo} onChange={(event) => handleChange("houseNo", event.target.value)} /></Field>
              <Field label={copy.societyName}><Input required value={form.societyName} onChange={(event) => handleChange("societyName", event.target.value)} /></Field>
              <Field label={copy.locality}><Input required value={form.locality} onChange={(event) => handleChange("locality", event.target.value)} /></Field>
              <Field label={copy.landmark}><Input value={form.landmark} onChange={(event) => handleChange("landmark", event.target.value)} /></Field>
              <Field label={copy.city}><Input required value={form.city} onChange={(event) => handleChange("city", event.target.value)} /></Field>
              <Field label={copy.state}>
                <Select<Option, false>
                  inputId="state"
                  unstyled
                  isSearchable
                  options={localizedStateOptions}
                  value={localizedStateOptions.find((option) => option.value === form.state) || null}
                  onChange={(option) => handleChange("state", option?.value || "")}
                  placeholder={copy.selectState}
                  noOptionsMessage={() => copy.noOptions}
                  classNames={selectClassNames}
                />
              </Field>
              <Field label={copy.pincode}><Input required inputMode="numeric" maxLength={6} value={form.pincode} onChange={(event) => handleChange("pincode", event.target.value.replace(/\D/g, "").slice(0, 6))} /></Field>
              <Field label={copy.country}><Input value={form.country} onChange={(event) => handleChange("country", event.target.value)} /></Field>
              <Field label={copy.pradesh}>
                <Select<Option, false>
                  inputId="pradeshId"
                  unstyled
                  isSearchable={false}
                  isLoading={hierarchyLoading}
                  isDisabled={hierarchyLoading || hierarchyError}
                  options={pradeshOptions}
                  value={pradeshOptions.find((option) => option.value === form.pradeshId) || null}
                  onChange={(option) => {
                    const nextPradeshId = option?.value || ""
                    setForm((current) => ({
                      ...current,
                      pradeshId: nextPradeshId,
                      mandalName: "",
                    }))
                  }}
                  placeholder={copy.selectPradesh}
                  noOptionsMessage={() => copy.noOptions}
                  classNames={selectClassNames}
                />
              </Field>
              <Field label={copy.mandal}>
                <Select<Option, false>
                  inputId="mandalName"
                  unstyled
                  isSearchable={false}
                  isDisabled={!form.pradeshId || hierarchyLoading || hierarchyError}
                  options={mandalOptions}
                  value={mandalOptions.find((option) => option.value === form.mandalName) || null}
                  onChange={(option) => handleChange("mandalName", option?.value || "")}
                  placeholder={form.pradeshId ? copy.selectMandal : copy.selectPradesh}
                  noOptionsMessage={() => copy.noOptions}
                  classNames={selectClassNames}
                />
              </Field>
              <Field label={copy.referencePersonName}>
                <Input required value={form.referencePersonName} onChange={(event) => handleChange("referencePersonName", event.target.value)} />
              </Field>
              <Field label={copy.referencePersonPhoneNo}>
                <div className="space-y-2">
                  <Input
                    required
                    inputMode="numeric"
                    maxLength={10}
                    value={form.referencePersonPhoneNo}
                    onChange={(event) => handleChange("referencePersonPhoneNo", event.target.value.replace(/\D/g, "").slice(0, 10))}
                  />
                  {isReferencePhoneInvalid ? <p className="text-xs text-[#922020]">{copy.invalidPhone}</p> : null}
                </div>
              </Field>
            </CardContent>
          </Card>

          <Card className="border-[#f0dcc6] bg-white/95 shadow-[0_16px_60px_rgba(110,57,0,0.08)]">
            <CardHeader>
              <CardTitle className="text-[#7b1017]">{copy.sevaInfo}</CardTitle>
            </CardHeader>
            <CardContent className="grid gap-5 md:grid-cols-2">
              <Field className="md:col-span-2" label={copy.sevaAvailableDates}>
                <div className="space-y-3">
                  <Popover open={isSevaDatePickerOpen} onOpenChange={setIsSevaDatePickerOpen}>
                    <PopoverTrigger asChild>
                      <Button
                        type="button"
                        variant="outline"
                        className="h-11 w-full justify-start border-input bg-background px-3 text-left font-normal text-foreground hover:bg-accent/40"
                      >
                        <CalendarDays className="mr-2 size-4 text-primary" />
                        <span className={cn(!form.sevaAvailableFrom || !form.sevaAvailableTo ? "text-muted-foreground" : "text-foreground")}>{sevaDateRangeLabel}</span>
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-auto border-border bg-popover p-0" align="start">
                      <Calendar
                        mode="range"
                        numberOfMonths={2}
                        defaultMonth={SEVA_DATE_MIN_VALUE}
                        selected={sevaDateRange}
                        onSelect={handleSevaDateRangeChange}
                        disabled={(date) => date < SEVA_DATE_MIN_VALUE || date > SEVA_DATE_MAX_VALUE}
                      />
                    </PopoverContent>
                  </Popover>
                </div>
              </Field>
              <Field className="md:col-span-2" label={copy.availableSevas}>
                <div className="space-y-4">
                  <Select<Option, true>
                    unstyled
                    isMulti
                    options={localizedSevaOptions}
                    value={selectedSevaOptions}
                    onChange={(options) => handleSevaOptionsChange(options)}
                    placeholder={copy.selectSevas}
                    noOptionsMessage={() => copy.noOptions}
                    classNames={selectClassNames}
                  />

                  {selectedSevaOptions.map((selectedOption) => {
                    const option = getNimitSevakSevaOption(selectedOption.value)
                    const selection = sevaSelections.find((entry) => entry.sevaCode === selectedOption.value)
                    if (!option || !selection) return null

                    const localizedSubSevaOptions = (option.subSevas || []).map((subOption) => ({
                      value: subOption.value,
                      label: getSubSevaLabel(subOption),
                    }))
                    const selectedSubSevaOptions = localizedSubSevaOptions.filter((subOption) => selection.subSevaCodes.includes(subOption.value))
                    const influencerLinkSubOptions = (option.subSevas || []).filter(
                      (subOption) => subOption.requiresPageLink && selection.subSevaCodes.includes(subOption.value),
                    )

                    return (
                      <div key={option.value} className="rounded-2xl border border-[#ead4bd] bg-[#fff9f2] p-4 space-y-4">
                        <div className="text-sm font-semibold leading-6 text-[#4b3727]">{selectedOption.label}</div>

                        {option.subSevas?.length ? (
                          <div className="space-y-2">
                            <Label className="text-xs text-[#8b6b4f]">{copy.subSevas}</Label>
                            <Select<Option, true>
                              unstyled
                              isMulti
                              options={localizedSubSevaOptions}
                              value={selectedSubSevaOptions}
                              onChange={(options) => handleSubSevaOptionsChange(option.value, options)}
                              placeholder={copy.selectSubSevas}
                              noOptionsMessage={() => copy.noOptions}
                              classNames={selectClassNames}
                            />
                          </div>
                        ) : null}

                        {influencerLinkSubOptions.length ? (
                          <div className="grid gap-3 sm:grid-cols-2">
                            {influencerLinkSubOptions.map((subOption) => (
                              <div key={subOption.value} className="space-y-2 rounded-xl border border-[#eddcc7] bg-white p-3">
                                <Label className="text-xs text-[#8b6b4f]">{`${getSubSevaLabel(subOption)} ${copy.pageLink}`}</Label>
                                <Input
                                  value={selection.pageLinks[subOption.value] || ""}
                                  onChange={(event) =>
                                    updateSevaSelection(option.value, (current) => ({
                                      ...current,
                                      pageLinks: {
                                        ...current.pageLinks,
                                        [subOption.value]: event.target.value,
                                      },
                                    }))
                                  }
                                  placeholder="https://..."
                                />
                              </div>
                            ))}
                          </div>
                        ) : null}

                        {option.requiresTextInput ? (
                          <div className="space-y-2">
                            <Label className="text-xs text-[#8b6b4f]">{t(option.textInputLabelKey || "nimitSevak.otherSevaDetails", option.textInputLabel || copy.otherSevaDetails)}</Label>
                            <Input
                              value={selection.customValue || ""}
                              onChange={(event) =>
                                updateSevaSelection(option.value, (current) => ({
                                  ...current,
                                  customValue: event.target.value,
                                }))
                              }
                              placeholder={t(option.textInputPlaceholderKey || "nimitSevak.otherSevaDetailsPlaceholder", option.textInputPlaceholder || copy.otherSevaDetailsPlaceholder)}
                            />
                          </div>
                        ) : null}
                      </div>
                    )
                  })}
                </div>
              </Field>
              <Field className="md:col-span-2" label=" ">
                <label className="flex items-start gap-3 rounded-2xl border border-[#ebd1b5] bg-[#fffaf3] px-4 py-4">
                  <Checkbox
                    checked={form.nightShiftAvailable}
                    onCheckedChange={(value) => setForm((current) => ({ ...current, nightShiftAvailable: Boolean(value) }))}
                    className="mt-0.5 data-[state=checked]:border-[#9f1d20] data-[state=checked]:bg-[#9f1d20]"
                  />
                  <span className="text-sm font-medium leading-6 text-[#4b3727]">{copy.nightShiftAvailable}</span>
                </label>
              </Field>
            </CardContent>
          </Card>

          <Card className="border-[#f0dcc6] bg-white/95 shadow-[0_16px_60px_rgba(110,57,0,0.08)]">
            <CardHeader>
              <CardTitle className="text-[#7b1017]">{copy.vehicleInfo}</CardTitle>
            </CardHeader>
            <CardContent className="grid gap-5 md:grid-cols-2">
              <Field label={copy.drivableVehicles}>
                <Select<Option, true>
                  unstyled
                  isMulti
                  options={vehicleOptions}
                  value={selectedDrivableVehicleOptions}
                  onChange={(options) => setDrivableVehicles(options.map((option) => option.value))}
                  placeholder={copy.selectVehicles}
                  noOptionsMessage={() => copy.noOptions}
                  classNames={selectClassNames}
                />
              </Field>
              <Field label={copy.availableVehicles}>
                <Select<Option, true>
                  unstyled
                  isMulti
                  options={vehicleOptions}
                  value={selectedAvailableVehicleOptions}
                  onChange={(options) => {
                    const nextValues = options.map((option) => option.value)
                    setAvailableVehicles(nextValues)

                    if (!nextValues.length) {
                      setForm((current) => ({
                        ...current,
                        vehicleAvailableFrom: "",
                        vehicleAvailableTo: "",
                      }))
                      setIsVehicleDatePickerOpen(false)
                    }
                  }}
                  placeholder={copy.selectVehicles}
                  noOptionsMessage={() => copy.noOptions}
                  classNames={selectClassNames}
                />
              </Field>
              <Field className="md:col-span-2" label={copy.vehicleAvailableDates}>
                <div className="space-y-3">
                  <Popover open={isVehicleDatePickerOpen} onOpenChange={setIsVehicleDatePickerOpen}>
                    <PopoverTrigger asChild>
                      <Button
                        type="button"
                        variant="outline"
                        disabled={!availableVehicles.length}
                        className="h-11 w-full justify-start border-input bg-background px-3 text-left font-normal text-foreground hover:bg-accent/40 disabled:cursor-not-allowed disabled:text-muted-foreground"
                      >
                        <CalendarDays className="mr-2 size-4 text-primary" />
                        <span className={cn(!form.vehicleAvailableFrom || !form.vehicleAvailableTo ? "text-muted-foreground" : "text-foreground")}>{vehicleDateRangeLabel}</span>
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-auto border-border bg-popover p-0" align="start">
                      <Calendar
                        mode="range"
                        numberOfMonths={2}
                        defaultMonth={SEVA_DATE_MIN_VALUE}
                        selected={vehicleDateRange}
                        onSelect={handleVehicleDateRangeChange}
                        disabled={(date) => date < SEVA_DATE_MIN_VALUE || date > SEVA_DATE_MAX_VALUE}
                      />
                    </PopoverContent>
                  </Popover>
                </div>
              </Field>
            </CardContent>
          </Card>

          <Card className="border-[#f0dcc6] bg-white/95 shadow-[0_16px_60px_rgba(110,57,0,0.08)]">
            <CardHeader>
              <CardTitle className="text-[#7b1017]">{copy.photoInfo}</CardTitle>
              <CardDescription>{copy.photoInfoHint}</CardDescription>
            </CardHeader>
            <CardContent className="grid gap-4 md:grid-cols-2">
              <Field label={copy.profilePhoto}>
                <label className="flex cursor-pointer flex-col items-center justify-center gap-3 rounded-2xl border border-dashed border-[#d8b18c] bg-[#fff8f1] px-6 py-10 text-center transition hover:border-[#cf7d31] hover:bg-[#fff2e1]">
                  <div className="rounded-full bg-[#fde8c4] p-3 text-[#9f1d20]"><Upload className="size-6" /></div>
                  <div className="space-y-1">
                    <p className="font-semibold text-[#6b2c10]">{profilePhoto?.name || copy.profilePhotoPrompt}</p>
                    <p className="text-sm text-[#7d6b5b]">{copy.profilePhotoHint}</p>
                  </div>
                  <input
                    required
                    type="file"
                    accept=".png,.jpeg,.jpg,image/png,image/jpeg"
                    className="hidden"
                    onChange={(event) => setProfilePhoto(event.target.files?.[0] || null)}
                  />
                </label>
              </Field>
              <Field label={copy.aadharCardImage}>
                <label className="flex cursor-pointer flex-col items-center justify-center gap-3 rounded-2xl border border-dashed border-[#d8b18c] bg-[#fff8f1] px-6 py-10 text-center transition hover:border-[#cf7d31] hover:bg-[#fff2e1]">
                  <div className="rounded-full bg-[#fde8c4] p-3 text-[#9f1d20]"><Upload className="size-6" /></div>
                  <div className="space-y-1">
                    <p className="font-semibold text-[#6b2c10]">{aadharCardImage?.name || copy.aadharCardPrompt}</p>
                    <p className="text-sm text-[#7d6b5b]">{copy.aadharCardImageHint}</p>
                  </div>
                  <input
                    required
                    type="file"
                    accept=".png,.jpeg,.jpg,.pdf,image/png,image/jpeg,application/pdf"
                    className="hidden"
                    onChange={(event) => setAadharCardImage(event.target.files?.[0] || null)}
                  />
                </label>
              </Field>

              {hierarchyLoading && (
                <div className="flex items-center gap-2 rounded-md border border-[#f1dfc8] bg-[#fffaf4] px-4 py-3 text-sm text-[#715f4f]">
                  <Loader2 className="size-4 animate-spin" />
                  {copy.hierarchyLoading}
                </div>
              )}

              {hierarchyError && (
                <div className="flex items-center gap-2 rounded-md border border-[#f7c7c7] bg-[#fff1f1] px-4 py-3 text-sm text-[#922020]">
                  <AlertCircle className="size-4" />
                  {copy.hierarchyError}
                </div>
              )}

              {errorMessage && (
                <div className="rounded-md border border-[#f7c7c7] bg-[#fff1f1] px-4 py-3 text-sm text-[#922020] md:col-span-2">{errorMessage}</div>
              )}

              <Button type="submit" disabled={isSubmitting || hierarchyLoading} className="h-11 w-full bg-[#9f1d20] text-base font-semibold hover:bg-[#7f1619] md:col-span-2 sm:w-auto sm:px-8">
                {isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
                {isSubmitting ? copy.submitting : copy.next}
              </Button>
            </CardContent>
          </Card>
        </form>

        <ConditionsModal
          open={isConditionsModalOpen}
          title={copy.conditionsTitle}
          intro={copy.conditionsIntro}
          points={conditionPoints}
          acceptanceLabel={copy.conditionsAcceptLabel}
          accepted={hasAcceptedConditions}
          acceptanceError={conditionsError}
          errorMessage={errorMessage}
          isSubmitting={isSubmitting}
          cancelLabel={copy.conditionsCancel}
          confirmLabel={copy.conditionsConfirm}
          onAcceptedChange={(checked) => {
            setHasAcceptedConditions(checked)
            if (checked) setConditionsError("")
          }}
          onCancel={closeConditionsModal}
          onConfirm={handleConfirmSubmit}
        />
      </div>
    </section>
  )
}

function Field({
  label,
  className,
  children,
}: {
  label: string
  className?: string
  children: React.ReactNode
}) {
  return (
    <div className={cn("space-y-2", className)}>
      <Label className="text-[#5a4130]">{label}</Label>
      {children}
    </div>
  )
}

function ConditionsModal({
  open,
  title,
  intro,
  points,
  acceptanceLabel,
  accepted,
  acceptanceError,
  errorMessage,
  isSubmitting,
  cancelLabel,
  confirmLabel,
  onAcceptedChange,
  onCancel,
  onConfirm,
}: ConditionsModalProps) {
  if (!open) return null

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-[#3b1c0e]/55 px-4 py-4 backdrop-blur-sm sm:items-center sm:py-6">
      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby="nimit-sevak-conditions-title"
        className="my-auto flex max-h-[calc(100dvh-2rem)] w-full max-w-2xl flex-col overflow-hidden rounded-[1.75rem] border border-[#efcfaf] bg-[linear-gradient(180deg,_#fffdf8_0%,_#fff4e7_100%)] shadow-[0_32px_120px_rgba(61,24,0,0.25)]"
      >
        <div className="border-b border-[#efd8bf] px-6 py-5 sm:px-8">
          <h2 id="nimit-sevak-conditions-title" className="text-2xl font-black tracking-tight text-[#7b1017]">
            {title}
          </h2>
          <p className="mt-2 text-sm leading-6 text-[#6e5a49]">{intro}</p>
        </div>

        <div className="flex-1 space-y-5 overflow-y-auto px-6 py-5 sm:px-8">
          <ol className="space-y-3 text-sm leading-7 text-[#4b3727]">
            {points.map((point, index) => (
              <li key={`${index + 1}-${point}`} className="flex gap-3 rounded-2xl border border-[#f1dfcb] bg-white/80 px-4 py-3 shadow-xs">
                <span className="mt-0.5 inline-flex size-6 shrink-0 items-center justify-center rounded-full bg-[#fff0dd] text-xs font-bold text-[#9f1d20]">
                  {index + 1}
                </span>
                <span>{point}</span>
              </li>
            ))}
          </ol>

          <label className="flex items-start gap-3 rounded-2xl border border-[#ebd1b5] bg-[#fffaf3] px-4 py-4">
            <Checkbox
              checked={accepted}
              onCheckedChange={(value) => onAcceptedChange(Boolean(value))}
              className="mt-0.5 data-[state=checked]:border-[#9f1d20] data-[state=checked]:bg-[#9f1d20]"
            />
            <span className="text-sm font-medium leading-6 text-[#4b3727]">{acceptanceLabel}</span>
          </label>

          {acceptanceError && (
            <div className="rounded-md border border-[#f7c7c7] bg-[#fff1f1] px-4 py-3 text-sm text-[#922020]">{acceptanceError}</div>
          )}

          {errorMessage && (
            <div className="rounded-md border border-[#f7c7c7] bg-[#fff1f1] px-4 py-3 text-sm text-[#922020]">{errorMessage}</div>
          )}
        </div>

        <div className="flex flex-col gap-3 border-t border-[#efd8bf] px-6 py-5 sm:flex-row sm:justify-end sm:px-8">
          <Button type="button" variant="outline" className="border-[#d5b18d] bg-white text-[#74462b] hover:bg-[#fff4e8]" onClick={onCancel} disabled={isSubmitting}>
            {cancelLabel}
          </Button>
          <Button
            type="button"
            className="bg-[#9f1d20] hover:bg-[#7f1619] disabled:bg-[#d7aaa2] disabled:text-white/85"
            onClick={onConfirm}
            disabled={isSubmitting || !accepted}
          >
            {isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
            {confirmLabel}
          </Button>
        </div>
      </div>
    </div>
  )
}