"use client";

import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { DatePickerInput } from "@/components/ui/date-picker-input";
import { Card, CardContent } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { apiRequest, apiUrl, isApiRequestCanceled, mediaUrl } from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";
import { useAuth } from "@/lib/auth-context";
import { useLanguage } from "@/lib/i18n";
import { DISTRICTS, EXPERTISE_AREAS, LANGUAGES } from "@/lib/types";
import {
  Loader2,
  CheckCircle2,
  ArrowLeft,
  ArrowRight,
  Edit,
  AlertTriangle,
  Eye,
  EyeOff,
  Camera,
  X,
  Info,
  Check,
  Upload,
  Trash2,
  FileText,
  MapPin,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { toast } from "react-toastify";

const steps = [
  {
    id: 1,
    title: "register.personalInfo",
    description: "register.basicDetails",
  },
  {
    id: 2,
    title: "register.professional",
    description: "register.experienceSkills",
  },
  { id: 3, title: "register.location", description: "register.areasOperation" },
  {
    id: 4,
    title: "register.documents",
    description: "register.uploadDocuments",
  },
  { id: 5, title: "register.password", description: "register.secureAccount" },
  { id: 6, title: "register.review", description: "register.confirmDetails" },
] as const;

type RegistrationOption = {
  id?: string | number;
  uuid?: string;
  district_uuid?: string;
  course_uuid?: string | null;
  title?: string;
  name?: string;
  name_hi?: string | null;
  district_name?: string;
  document_type?: string;
  course_location?: string | null;
  course_location_hi?: string | null;
  title_hi?: string | null;
  status?: string;
  is_active?: boolean | number | string;
  is_required?: boolean | number | string;
  format?: string | null;
  max_size?: string | number | null;
  district_uuids?: string[] | null;
  districts?: RegistrationOption[] | null;
  locations?: RegistrationOption[] | null;
  district?: RegistrationOption | null;
  course?: RegistrationOption | null;
  course_districts?: RegistrationOption[] | null;
};

type GuideSupportingDocument = {
  id?: string | number;
  uuid?: string;
  document_type_uuid?: string;
  document_type_id?: string | number;
  document_type?: RegistrationOption | string | null;
  title?: string;
  name?: string;
  file?: string | null;
  file_path?: string | null;
  file_url?: string | null;
  document_url?: string | null;
  original_name?: string | null;
  file_name?: string | null;
};

type GuideIdentityDetail = {
  father_name?: string | null;
  mother_name?: string | null;
  date_of_birth?: string | null;
  dateOfBirth?: string | null;
  dob?: string | null;
};

type GuideRegistrationDetail = {
  uuid?: string;
  id?: string | number;
  name?: string;
  email?: string;
  phone?: string;
  profile_image?: string | null;
  profile_image_url?: string | null;
  father_name?: string | null;
  mother_name?: string | null;
  date_of_birth?: string | null;
  dateOfBirth?: string | null;
  dob?: string | null;
  address?: string;
  year_of_experience?: string | number;
  experience?: string | number;
  company_name?: string | null;
  companyName?: string | null;
  bio?: string;
  course_uuid?: string | null;
  course?: RegistrationOption | null;
  course_district_uuid?: string | null;
  course_district?: RegistrationOption | null;
  course_location_uuid?: string | null;
  course_location?: RegistrationOption | string | null;
  languages?: RegistrationOption[];
  language_uuids?: string[];
  skills?: RegistrationOption[];
  skill_uuids?: string[];
  expertise?: RegistrationOption[];
  locations?: RegistrationOption[];
  location_uuids?: string[];
  district_uuid?: string | null;
  districts?: RegistrationOption[];
  district?: RegistrationOption | null;
  supporting_documents?: GuideSupportingDocument[];
  documents?: GuideSupportingDocument[];
  identity_card_detail?: GuideIdentityDetail | null;
  identity_card_details?: GuideIdentityDetail | null;
  reject_reason?: string | null;
  rejected_reason?: string | null;
  rejection_reason?: string | null;
};

type GuideRegistrationOptionsResponse = {
  statusCode: number;
  success: boolean;
  data?: {
    languages?: RegistrationOption[];
    skills?: RegistrationOption[];
    locations?: RegistrationOption[];
    districts?: RegistrationOption[];
    courses?: RegistrationOption[];
    course_locations?: RegistrationOption[];
    course_districts?: RegistrationOption[];
    document_types?: RegistrationOption[];
  };
  message?: string;
  message_hi?: string;
};

type GuideRegistrationResponse = {
  statusCode: number;
  success: boolean;
  data?: unknown;
  errors?: unknown;
  message?: string;
  message_hi?: string;
};

type GuideRegistrationDetailResponse = {
  statusCode?: number;
  success?: boolean;
  data?:
    | GuideRegistrationDetail
    | {
        guide?: GuideRegistrationDetail;
        user?: GuideRegistrationDetail;
      };
  guide?: GuideRegistrationDetail;
  message?: string;
  message_hi?: string;
};

type AvailabilityCheckResponse = {
  statusCode?: number;
  success?: boolean;
  data?: unknown;
  errors?: unknown;
  message?: string;
  message_hi?: string;
};

type AvailabilityStatus = "idle" | "checking" | "available" | "unavailable";

type AvailabilityState = {
  status: AvailabilityStatus;
  message: string;
};

type GuideRegistrationOptions = {
  languages: RegistrationOption[];
  skills: RegistrationOption[];
  locations: RegistrationOption[];
  districts: RegistrationOption[];
  courses: RegistrationOption[];
  courseLocations: RegistrationOption[];
  documentTypes: RegistrationOption[];
};

const createFallbackOptions = (titles: string[]): RegistrationOption[] =>
  titles.map((title, index) => ({
    uuid: `${title}-${index}`,
    title,
    status: "active",
  }));

const fallbackRegistrationOptions: GuideRegistrationOptions = {
  languages: createFallbackOptions(LANGUAGES),
  skills: createFallbackOptions(EXPERTISE_AREAS),
  locations: createFallbackOptions(DISTRICTS),
  districts: [],
  courses: [],
  courseLocations: [],
  documentTypes: [],
};

const getOptionArray = <T,>(options?: T[] | null) =>
  Array.isArray(options) ? options : [];

const getActiveOptions = (options?: RegistrationOption[] | null) =>
  getOptionArray(options).filter((option) => option.status !== "inactive");

const getOptionTitle = (option: RegistrationOption) =>
  option.title ||
  option.name ||
  option.district_name ||
  option.course_location ||
  option.district?.title ||
  option.district?.name ||
  option.district?.district_name ||
  option.uuid ||
  "";

const getOptionTitleHi = (option: RegistrationOption) =>
  option.title_hi ||
  option.name_hi ||
  option.course_location_hi ||
  option.district?.title_hi ||
  option.district?.name_hi ||
  null;

const getOptionValue = (option: RegistrationOption) =>
  option.uuid || option.district_uuid || getOptionTitle(option);

const getOptionsOrFallback = (
  options: RegistrationOption[] | undefined,
  fallback: RegistrationOption[],
) => {
  const activeOptions = getActiveOptions(getOptionArray(options));

  return activeOptions.length > 0 ? activeOptions : fallback;
};

const isRecord = (value: unknown): value is Record<string, unknown> =>
  Boolean(value) && typeof value === "object" && !Array.isArray(value);

const humanizeFieldName = (field: string) =>
  field.replace(/_/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());

const collectValidationMessages = (
  value: unknown,
  parentKey = "",
): string[] => {
  if (!value) {
    return [];
  }

  if (typeof value === "string") {
    return parentKey ? [`${humanizeFieldName(parentKey)}: ${value}`] : [value];
  }

  if (Array.isArray(value)) {
    return value.flatMap((item) => collectValidationMessages(item, parentKey));
  }

  if (isRecord(value)) {
    return Object.entries(value).flatMap(([key, item]) =>
      collectValidationMessages(item, key),
    );
  }

  return [];
};

const getValidationMessages = (response: GuideRegistrationResponse) => [
  ...collectValidationMessages(response.errors),
  ...collectValidationMessages(response.data),
];

const initialAvailabilityState: AvailabilityState = {
  status: "idle",
  message: "",
};

const getBooleanField = (value: unknown, field: string) => {
  if (!isRecord(value) || typeof value[field] !== "boolean") {
    return undefined;
  }

  return value[field] as boolean;
};

const getAvailabilityResult = (
  response: Response,
  result: AvailabilityCheckResponse,
) => {
  const available = getBooleanField(result.data, "available");
  const exists = getBooleanField(result.data, "exists");

  if (typeof available === "boolean") {
    return available;
  }

  if (typeof exists === "boolean") {
    return !exists;
  }

  return response.ok && result.success !== false;
};

const valueToString = (value: unknown) =>
  value === null || value === undefined ? "" : String(value);

const valueToDateDisplay = (value: unknown) => {
  const date = valueToString(value).slice(0, 10);
  const isoMatch = date.match(/^(\d{4})-(\d{2})-(\d{2})$/);

  return isoMatch ? `${isoMatch[3]}/${isoMatch[2]}/${isoMatch[1]}` : date;
};

const dateDisplayToApi = (value: string) => {
  const match = value.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);

  return match ? `${match[3]}-${match[2]}-${match[1]}` : "";
};

const isValidDateOfBirth = (value: string) => {
  const match = value.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
  if (!match) return false;

  const [, day, month, year] = match;
  const date = new Date(Number(year), Number(month) - 1, Number(day));

  return (
    date.getFullYear() === Number(year) &&
    date.getMonth() === Number(month) - 1 &&
    date.getDate() === Number(day) &&
    date <= new Date()
  );
};

const dateOfBirthToApi = (value: string) => {
  const [day, month, year] = value.split("/");
  return `${year}-${month}-${day}`;
};

const getDetailFromResponse = (
  result: GuideRegistrationDetailResponse,
): GuideRegistrationDetail | undefined => {
  if (result.guide) return result.guide;
  if (!result.data) return undefined;
  const data = result.data;

  if (isRecord(data) && ("guide" in data || "user" in data)) {
    return (data.guide || data.user) as GuideRegistrationDetail | undefined;
  }

  return data as GuideRegistrationDetail;
};

const selectedOptionValues = (options?: RegistrationOption[]) =>
  (options || [])
    .map((option) => getOptionValue(option))
    .filter((value): value is string => Boolean(value));

const selectedDetailValues = (
  options?: RegistrationOption[],
  uuids?: string[],
) => {
  const values = selectedOptionValues(options);

  return values.length ? values : uuids || [];
};

const getIdentityDetail = (
  detail: GuideRegistrationDetail,
): GuideIdentityDetail =>
  detail.identity_card_detail || detail.identity_card_details || {};

const appendFormValue = (
  payload: FormData,
  key: string,
  value: string | number | boolean | undefined | null,
) => {
  if (value === undefined || value === null || value === "") {
    return;
  }

  payload.append(key, String(value));
};

const appendFormArray = (payload: FormData, key: string, values: string[]) => {
  values.forEach((value) => payload.append(`${key}[]`, value));
};

const allowedDocumentExtensions = ["pdf", "jpg", "jpeg", "png", "webp"];
const defaultDocumentMaxSizeKb = 2000;
const profileImageMaxSizeBytes = 2 * 1024 * 1024;
const maxSelectableOptions = 5;

const getDocumentTypeTitle = (documentType: RegistrationOption) =>
  documentType.title ||
  documentType.name ||
  documentType.document_type ||
  "Document";

const getDocumentTypeKey = (documentType: RegistrationOption) =>
  documentType.uuid ||
  String(documentType.id || getDocumentTypeTitle(documentType));

const isActiveDocumentType = (documentType: RegistrationOption) => {
  if (String(documentType.status || "active").toLowerCase() === "inactive") {
    return false;
  }

  return ![false, 0, "0", "false"].includes(
    documentType.is_active as boolean | number | string,
  );
};

const isRequiredDocumentType = (documentType: RegistrationOption) => {
  const required = documentType.is_required;

  if (typeof required === "string") {
    return ["yes", "true", "1", "required"].includes(
      required.trim().toLowerCase(),
    );
  }

  return Boolean(required);
};

const getDocumentFormat = (documentType: RegistrationOption) => {
  const format = String(documentType.format || "")
    .trim()
    .toLowerCase();
  return !format || format === "all"
    ? allowedDocumentExtensions.join(", ")
    : format;
};

const getDocumentExtensions = (documentType: RegistrationOption) =>
  getDocumentFormat(documentType)
    .split(",")
    .map((extension) => extension.trim().replace(/^\./, ""))
    .filter((extension) => allowedDocumentExtensions.includes(extension));

const getDocumentAccept = (documentType: RegistrationOption) =>
  getDocumentExtensions(documentType)
    .map((extension) => `.${extension}`)
    .join(",");

const getDocumentMaxSizeKb = (documentType: RegistrationOption) => {
  if (!documentType.max_size) return defaultDocumentMaxSizeKb;

  const value = String(documentType.max_size).trim().toLowerCase();
  const amount = Number.parseFloat(value);
  if (!Number.isFinite(amount) || amount <= 0) return defaultDocumentMaxSizeKb;

  return value.includes("mb") ? amount * 1024 : amount;
};

const getDocumentMaxSizeLabel = (documentType: RegistrationOption) => {
  const sizeKb = getDocumentMaxSizeKb(documentType);
  return Number.isInteger(sizeKb)
    ? `${sizeKb} KB Max.`
    : `${sizeKb.toFixed(1)} KB Max.`;
};

const getFileExtension = (fileName: string) =>
  fileName.split(".").pop()?.toLowerCase() || "";

const getSupportingDocumentTypeKey = (document: GuideSupportingDocument) => {
  if (document.document_type_uuid) return document.document_type_uuid;
  if (document.document_type_id) return String(document.document_type_id);
  if (typeof document.document_type === "object" && document.document_type) {
    return getDocumentTypeKey(document.document_type);
  }

  return typeof document.document_type === "string"
    ? document.document_type
    : String(document.title || document.name || "");
};

const getSupportingDocumentPath = (document: GuideSupportingDocument) =>
  String(
    document.file_url ||
      document.document_url ||
      document.file_path ||
      document.file ||
      "",
  );

const getSupportingDocumentName = (document: GuideSupportingDocument) =>
  String(
    document.original_name ||
      document.file_name ||
      document.title ||
      document.name ||
      getSupportingDocumentPath(document).split("/").pop() ||
      "Uploaded document",
  );

type ExistingRegistrationDocument = {
  name: string;
  path: string;
};

const getRegistrationDocumentStatusLabel = (
  file?: File,
  existingDocument?: ExistingRegistrationDocument,
) => {
  if (file) return "Selected";
  if (existingDocument) return "Uploaded";
  return "";
};

function DocumentQualityTip({ label, ok }: { label: string; ok: boolean }) {
  return (
    <div className="flex flex-col items-center gap-2 rounded-xl border border-sky-200 bg-sky-50 p-3 text-center">
      <div className="relative h-12 w-16 rounded-md border border-sky-200 bg-white">
        <div className="absolute left-2 top-2 h-2 w-8 rounded bg-slate-300/70" />
        <div className="absolute bottom-2 right-2 h-3 w-4 rounded bg-cyan-200/80" />
        <span
          className={cn(
            "absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full text-white",
            ok ? "bg-emerald-600" : "bg-red-600",
          )}
        >
          {ok ? <Check className="h-3 w-3" /> : <X className="h-3 w-3" />}
        </span>
      </div>
      <p className="text-xs font-bold text-muted-foreground">{label}</p>
    </div>
  );
}

function PersonalGuideline({ text }: { text: string }) {
  const [label, ...details] = text.split(":");
  const hasLabel = details.length > 0;

  return (
    <p className="flex min-w-0 items-start gap-1.5">
      <span className="mt-px shrink-0 font-black text-[var(--theme-accent)]">
        -&gt;
      </span>
      <span>
        {hasLabel ? (
          <>
            <span className="font-black">{label}:</span>
            {details.join(":")}
          </>
        ) : (
          text
        )}
      </span>
    </p>
  );
}

function RegistrationDocumentRow({
  index,
  documentType,
  displayTitle,
  file,
  existingDocument,
  error,
  onUpload,
  onPreview,
  onDelete,
  uploadLabel,
  viewLabel,
  deleteLabel,
}: {
  index: number;
  documentType: RegistrationOption;
  displayTitle: string;
  file?: File;
  existingDocument?: ExistingRegistrationDocument;
  error?: string;
  onUpload: (file: File) => void;
  onPreview: () => void;
  onDelete: () => void;
  uploadLabel: string;
  viewLabel: string;
  deleteLabel: string;
}) {
  const inputRef = useRef<HTMLInputElement>(null);
  const title = displayTitle;
  const hasFile = Boolean(file || existingDocument);
  const fileName = file?.name || existingDocument?.name || "";
  const filePath = file?.name || existingDocument?.path || "";
  const statusLabel = getRegistrationDocumentStatusLabel(
    file,
    existingDocument,
  );

  return (
    <div className="grid gap-4 rounded-2xl bg-gray-50 p-4 md:grid-cols-[1fr_auto_auto] md:items-center">
      <div className="min-w-0">
        <div className="flex flex-wrap items-center gap-2">
          <p className="text-sm font-black text-foreground">
            {index}. {title}
            {isRequiredDocumentType(documentType) && (
              <span className="ml-1 text-red-600">*</span>
            )}
          </p>
          {hasFile && (
            <span className="rounded-full bg-amber-100 px-3 py-1 text-xs font-black text-amber-700">
              {statusLabel}
            </span>
          )}
        </div>
        {filePath && (
          <p className="mt-1 truncate text-xs font-semibold text-[var(--theme-primary)]">
            {filePath}
          </p>
        )}
        {error && (
          <p className="mt-1 text-xs font-semibold text-destructive">{error}</p>
        )}
      </div>

      <div className="flex items-center gap-2">
        <input
          ref={inputRef}
          type="file"
          accept={getDocumentAccept(documentType)}
          className="hidden"
          onChange={(event) => {
            const nextFile = event.target.files?.[0];
            if (nextFile) onUpload(nextFile);
            event.target.value = "";
          }}
        />
        <Button
          type="button"
          size="icon"
          onClick={() => inputRef.current?.click()}
          className={cn(
            "h-9 w-9 rounded-lg shadow-none",
            hasFile
              ? "bg-emerald-600 text-white hover:bg-emerald-700"
              : "bg-white text-[var(--theme-primary)] hover:bg-[var(--theme-surface)]",
          )}
          aria-label={hasFile ? `${title} uploaded` : `${uploadLabel} ${title}`}
          title={uploadLabel}
        >
          {hasFile ? (
            <Check className="h-4 w-4" />
          ) : (
            <Upload className="h-4 w-4" />
          )}
        </Button>
        <Button
          type="button"
          size="icon"
          variant="outline"
          disabled={!hasFile}
          onClick={onPreview}
          className="h-9 w-9 rounded-lg border-gray-200 bg-white text-[var(--theme-primary)] hover:bg-gray-100"
          aria-label={`${viewLabel} ${title}`}
          title={viewLabel}
        >
          <Eye className="h-4 w-4" />
        </Button>
        <Button
          type="button"
          size="icon"
          variant="outline"
          disabled={!hasFile}
          onClick={onDelete}
          className="h-9 w-9 rounded-lg border-gray-200 bg-white text-red-600 hover:bg-red-50 hover:text-red-700"
          aria-label={`${deleteLabel} ${title}`}
          title={deleteLabel}
        >
          <Trash2 className="h-4 w-4" />
        </Button>
      </div>

      <div className="min-w-[160px] text-xs font-semibold text-muted-foreground md:text-right">
        <p className="text-foreground">({getDocumentFormat(documentType)})</p>
        <p>{getDocumentMaxSizeLabel(documentType)}</p>
      </div>
    </div>
  );
}

const languageLabelsHi: Record<string, string> = {
  Hindi: "हिंदी",
  English: "अंग्रेज़ी",
  Garhwali: "गढ़वाली",
  Kumaoni: "कुमाऊँनी",
  Punjabi: "पंजाबी",
  Bengali: "बंगाली",
  Tamil: "तमिल",
  Telugu: "तेलुगु",
  French: "फ्रेंच",
  German: "जर्मन",
};

const expertiseLabelsHi: Record<string, string> = {
  "Char Dham Pilgrimage": "चार धाम यात्रा",
  "Adventure Tourism": "साहसिक पर्यटन",
  "Wildlife Safari": "वन्यजीव सफारी",
  "Cultural Heritage": "सांस्कृतिक विरासत",
  "Religious Tourism": "धार्मिक पर्यटन",
  "Eco Tourism": "ईको पर्यटन",
  "Photography Tours": "फोटोग्राफी टूर",
  Trekking: "ट्रेकिंग",
  "River Rafting": "रिवर राफ्टिंग",
};

const districtLabelsHi: Record<string, string> = {
  Dehradun: "देहरादून",
  Haridwar: "हरिद्वार",
  Rishikesh: "ऋषिकेश",
  Mussoorie: "मसूरी",
  Nainital: "नैनीताल",
  Almora: "अल्मोड़ा",
  Pithoragarh: "पिथौरागढ़",
  "Chamoli (Badrinath)": "चमोली (बद्रीनाथ)",
  "Uttarkashi (Gangotri/Yamunotri)": "उत्तरकाशी (गंगोत्री/यमुनोत्री)",
  "Rudraprayag (Kedarnath)": "रुद्रप्रयाग (केदारनाथ)",
  "Pauri Garhwal": "पौड़ी गढ़वाल",
  "Tehri Garhwal": "टिहरी गढ़वाल",
};

export default function RegisterPage() {
  const router = useRouter();
  const { user, isAuthenticated, isLoading } = useAuth();
  const { language, t } = useLanguage();
  const [currentStep, setCurrentStep] = useState(1);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  const [submitMessage, setSubmitMessage] = useState("");
  const [submitError, setSubmitError] = useState("");
  const [submitValidationMessages, setSubmitValidationMessages] = useState<
    string[]
  >([]);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [emailAvailability, setEmailAvailability] = useState<AvailabilityState>(
    initialAvailabilityState,
  );
  const [phoneAvailability, setPhoneAvailability] = useState<AvailabilityState>(
    initialAvailabilityState,
  );
  const [registrationOptions, setRegistrationOptions] =
    useState<GuideRegistrationOptions>(fallbackRegistrationOptions);
  const [isLoadingRegistrationOptions, setIsLoadingRegistrationOptions] =
    useState(true);
  const [registrationOptionsError, setRegistrationOptionsError] = useState("");
  const [isResubmitMode, setIsResubmitMode] = useState(false);
  const [resubmitUuid, setResubmitUuid] = useState("");
  const [isLoadingResubmit, setIsLoadingResubmit] = useState(false);
  const [resubmitReason, setResubmitReason] = useState("");
  const [existingProfileImage, setExistingProfileImage] = useState("");
  const [profileImagePreview, setProfileImagePreview] = useState("");
  const [profileImageError, setProfileImageError] = useState("");
  const [documentUploads, setDocumentUploads] = useState<Record<string, File>>(
    {},
  );
  const [existingDocuments, setExistingDocuments] = useState<
    Record<string, ExistingRegistrationDocument>
  >({});
  const [documentErrors, setDocumentErrors] = useState<Record<string, string>>(
    {},
  );
  const profileImageInputRef = useRef<HTMLInputElement>(null);

  const [formData, setFormData] = useState({
    // Personal Info
    name: "",
    email: "",
    profileImage: null as File | null,
    fatherName: "",
    motherName: "",
    dateOfBirth: "",
    districtUuid: "",
    password: "",
    confirmPassword: "",
    phone: "",
    address: "",
    // Professional
    experience: "",
    companyName: "",
    bio: "",
    courseUuid: "",
    courseLocationUuid: "",
    languages: [] as string[],
    expertise: [] as string[],
    // Location
    districts: [] as string[],
    // Agreement
    agreeTerms: false,
  });

  const updateField = (
    field: string,
    value: string | boolean | string[] | File | null,
  ) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  useEffect(() => {
    if (!formData.profileImage) {
      setProfileImagePreview("");
      return;
    }

    const nextPreview = URL.createObjectURL(formData.profileImage);
    setProfileImagePreview(nextPreview);

    return () => URL.revokeObjectURL(nextPreview);
  }, [formData.profileImage]);

  const getSelectionFieldLabel = (
    field: "languages" | "expertise" | "districts",
  ) =>
    field === "languages"
      ? t("register.languagesSpoken")
      : field === "expertise"
        ? t("register.areasExpertise")
        : t("register.location");

  const isSelectionLimitReached = (
    field: "languages" | "expertise" | "districts",
    item: string,
  ) =>
    formData[field].length >= maxSelectableOptions &&
    !formData[field].includes(item);

  const toggleArrayItem = (
    field: "languages" | "expertise" | "districts",
    item: string,
  ) => {
    if (isSelectionLimitReached(field, item)) {
      toast.error(
        `${getSelectionFieldLabel(field)}: You can select maximum ${maxSelectableOptions}.`,
        { toastId: `register-${field}-max-selection` },
      );
      return;
    }

    setFormData((prev) => {
      const selectedItems = prev[field];

      return {
        ...prev,
        [field]: selectedItems.includes(item)
          ? selectedItems.filter((i) => i !== item)
          : [...selectedItems, item],
      };
    });
  };

  const passwordRules = {
    length: formData.password.length >= 8,
    uppercase: /[A-Z]/.test(formData.password),
    number: /\d/.test(formData.password),
    special: /[^A-Za-z0-9]/.test(formData.password),
  };
  const passwordValid = Object.values(passwordRules).every(Boolean);
  const displayLanguage = (value: string) =>
    language === "hi" ? languageLabelsHi[value] || value : value;
  const displayExpertise = (value: string) =>
    language === "hi" ? expertiseLabelsHi[value] || value : value;
  const displayDistrict = (value: string) =>
    language === "hi" ? districtLabelsHi[value] || value : value;
  const displayRegistrationOption = (
    option: RegistrationOption,
    fallbackDisplay: (value: string) => string,
  ) => {
    if (language === "hi") {
      return getOptionTitleHi(option) || fallbackDisplay(getOptionTitle(option));
    }

    return getOptionTitle(option);
  };
  const findSelectedOptions = (
    selectedValues: string[] = [],
    options?: RegistrationOption[] | null,
  ) =>
    getOptionArray(selectedValues)
      .filter(Boolean)
      .map((value) =>
        getOptionArray(options).find(
          (option) =>
            getOptionValue(option) === value ||
            getOptionTitle(option) === value,
        ),
      )
      .filter((option): option is RegistrationOption => Boolean(option));
  const getSelectedUuids = (
    selectedValues: string[],
    options?: RegistrationOption[] | null,
  ) =>
    findSelectedOptions(selectedValues, options)
      .map((option) => option.uuid || option.district_uuid)
      .filter((uuid): uuid is string => Boolean(uuid));
  const selectedCourse = findSelectedOptions(
    [formData.courseUuid],
    registrationOptions.courses,
  )[0];
  const selectedCourseUuid = selectedCourse?.uuid || formData.courseUuid;
  const courseLocationOptions = selectedCourseUuid
    ? [
        ...(selectedCourse?.course_districts || []),
        ...registrationOptions.courseLocations.filter(
          (option) =>
            (option.course_uuid || option.course?.uuid) === selectedCourseUuid,
        ),
      ].filter(
        (option, index, options) =>
          options.findIndex(
            (item) => getOptionValue(item) === getOptionValue(option),
          ) === index,
      )
    : [];
  useEffect(() => {
    if (
      formData.courseLocationUuid &&
      !courseLocationOptions.some(
        (option) => getOptionValue(option) === formData.courseLocationUuid,
      )
    ) {
      updateField("courseLocationUuid", "");
    }
  }, [courseLocationOptions, formData.courseLocationUuid]);

  const profileImageSource =
    profileImagePreview || mediaUrl(existingProfileImage);
  const profileImageLabel =
    formData.profileImage?.name ||
    (existingProfileImage
      ? t("register.currentPhoto")
      : t("register.noProfileImageSelected"));
  const hasProfileImage = Boolean(
    formData.profileImage || existingProfileImage,
  );
  const activeDocumentTypes =
    registrationOptions.documentTypes.filter(isActiveDocumentType);
  const missingRequiredDocumentTypes = activeDocumentTypes.filter(
    (documentType) => {
      if (!isRequiredDocumentType(documentType)) return false;
      const key = getDocumentTypeKey(documentType);
      return !documentUploads[key] && !existingDocuments[key];
    },
  );
  const documentsValid =
    missingRequiredDocumentTypes.length === 0 &&
    Object.keys(documentErrors).length === 0;
  const personalInfoValid =
    Boolean(
      formData.name &&
      formData.email &&
      /^\d{10}$/.test(formData.phone) &&
      formData.address &&
      formData.fatherName &&
      formData.motherName &&
      formData.districtUuid &&
      isValidDateOfBirth(formData.dateOfBirth) &&
      hasProfileImage &&
      !profileImageError,
    ) &&
    (isResubmitMode ||
      (emailAvailability.status === "available" &&
        phoneAvailability.status === "available"));
  const getAvailabilityClassName = (status: AvailabilityStatus) =>
    cn(
      "flex items-center gap-2 text-xs font-medium",
      status === "available" && "text-emerald-600",
      status === "checking" && "text-muted-foreground",
      status === "unavailable" && "text-destructive",
    );

  const canProceed = () => {
    switch (currentStep) {
      case 1:
        return personalInfoValid;
      case 2:
        return (
          formData.experience &&
          formData.bio &&
          formData.courseUuid &&
          formData.courseLocationUuid &&
          formData.languages.length > 0 &&
          formData.expertise.length > 0
        );
      case 3:
        return formData.districts.length > 0;
      case 4:
        return (
          !isLoadingRegistrationOptions &&
          !registrationOptionsError &&
          documentsValid
        );
      case 5:
        if (isResubmitMode && !formData.password && !formData.confirmPassword) {
          return true;
        }

        return Boolean(
          passwordValid &&
          formData.confirmPassword &&
          formData.password === formData.confirmPassword,
        );
      case 6:
        return formData.agreeTerms;
      default:
        return false;
    }
  };

  const handleNext = () => {
    if (currentStep < 6) {
      setCurrentStep(currentStep + 1);
    }
  };

  const handleBack = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const handleProfileImageChange = (file?: File) => {
    if (!file) return;

    const allowedTypes = ["image/jpeg", "image/png"];
    if (!allowedTypes.includes(file.type)) {
      setProfileImageError(t("register.photoTypeError"));
    } else if (file.size > profileImageMaxSizeBytes) {
      setProfileImageError(t("register.photoSizeError"));
    } else {
      setProfileImageError("");
      updateField("profileImage", file);
    }

    if (profileImageInputRef.current) {
      profileImageInputRef.current.value = "";
    }
  };

  const clearProfileImageSelection = () => {
    updateField("profileImage", null);
    setProfileImageError("");

    if (profileImageInputRef.current) {
      profileImageInputRef.current.value = "";
    }
  };

  const handleDocumentUpload = (
    documentType: RegistrationOption,
    file: File,
  ) => {
    const key = getDocumentTypeKey(documentType);
    const extension = getFileExtension(file.name);
    const allowedExtensions = getDocumentExtensions(documentType);
    let error = "";

    if (
      !allowedDocumentExtensions.includes(extension) ||
      !allowedExtensions.includes(extension)
    ) {
      error = t("register.documentTypeError").replace(
        "{formats}",
        getDocumentFormat(documentType),
      );
    } else if (file.size > getDocumentMaxSizeKb(documentType) * 1024) {
      error = t("register.documentSizeError").replace(
        "{size}",
        getDocumentMaxSizeLabel(documentType).replace(" Max.", ""),
      );
    }

    if (error) {
      setDocumentErrors((previous) => ({ ...previous, [key]: error }));
      return;
    }

    setDocumentUploads((previous) => ({ ...previous, [key]: file }));
    setDocumentErrors((previous) => {
      const next = { ...previous };
      delete next[key];
      return next;
    });
  };

  const handleDocumentPreview = (documentType: RegistrationOption) => {
    const key = getDocumentTypeKey(documentType);
    const selectedFile = documentUploads[key];
    const previewUrl = selectedFile
      ? URL.createObjectURL(selectedFile)
      : mediaUrl(existingDocuments[key]?.path);

    if (!previewUrl) return;
    window.open(previewUrl, "_blank", "noopener,noreferrer");

    if (selectedFile) {
      window.setTimeout(() => URL.revokeObjectURL(previewUrl), 60_000);
    }
  };

  const handleDocumentDelete = (documentType: RegistrationOption) => {
    const key = getDocumentTypeKey(documentType);

    setDocumentUploads((previous) => {
      const next = { ...previous };
      delete next[key];
      return next;
    });
    setExistingDocuments((previous) => {
      const next = { ...previous };
      delete next[key];
      return next;
    });
    setDocumentErrors((previous) => {
      const next = { ...previous };
      delete next[key];
      return next;
    });
  };

  const buildRegistrationPayload = () => {
    const payload = new FormData();

    if (isResubmitMode) {
      payload.append("_method", "PUT");
      payload.append("status", "pending");
    }

    appendFormValue(payload, "name", formData.name.trim());
    appendFormValue(payload, "email", formData.email.trim());
    appendFormValue(payload, "phone", formData.phone.trim());
    appendFormValue(payload, "father_name", formData.fatherName.trim());
    appendFormValue(payload, "mother_name", formData.motherName.trim());
    appendFormValue(
      payload,
      "date_of_birth",
      dateOfBirthToApi(formData.dateOfBirth),
    );
    appendFormValue(payload, "district_uuid", formData.districtUuid);

    if (formData.profileImage) {
      payload.append("profile_image", formData.profileImage);
    }

    if (!isResubmitMode || formData.password) {
      appendFormValue(payload, "password", formData.password);
      appendFormValue(payload, "confirm_password", formData.confirmPassword);
    }

    appendFormValue(payload, "address", formData.address.trim());
    appendFormValue(payload, "year_of_experience", formData.experience);
    appendFormValue(payload, "company_name", formData.companyName.trim());
    appendFormValue(payload, "bio", formData.bio.trim());
    appendFormValue(payload, "course_uuid", formData.courseUuid);
    appendFormValue(payload, "course_district_uuid", formData.courseLocationUuid);
    appendFormArray(
      payload,
      "language_uuids",
      getSelectedUuids(formData.languages, registrationOptions.languages),
    );
    appendFormArray(
      payload,
      "skill_uuids",
      getSelectedUuids(formData.expertise, registrationOptions.skills),
    );
    appendFormArray(
      payload,
      "location_uuids",
      getSelectedUuids(formData.districts, registrationOptions.locations),
    );

    let supportingDocumentIndex = 0;
    activeDocumentTypes.forEach((documentType) => {
      const key = getDocumentTypeKey(documentType);
      const file = documentUploads[key];
      if (!file) return;

      payload.append(
        `supporting_documents[${supportingDocumentIndex}][document_type_uuid]`,
        documentType.uuid || key,
      );
      payload.append(
        `supporting_documents[${supportingDocumentIndex}][file]`,
        file,
      );
      supportingDocumentIndex += 1;
    });

    if (!isResubmitMode) {
      payload.append("declaration_accepted", formData.agreeTerms ? "1" : "0");
    }

    return payload;
  };

  const handleSubmit = async () => {
    setIsSubmitting(true);
    setSubmitError("");
    setSubmitMessage("");
    setSubmitValidationMessages([]);

    try {
      const payload = buildRegistrationPayload();

      const response = await apiRequest(
        apiUrl(
          isResubmitMode && resubmitUuid
            ? `/guide-registration/${resubmitUuid}`
            : "/guide-registration",
        ),
        {
          method: "POST",
          headers: {
            Accept: "application/json",
          },
          body: payload,
        },
      );
      const result = (await response.json()) as GuideRegistrationResponse;

      if (!response.ok || !result.success) {
        setSubmitValidationMessages(getValidationMessages(result));
        throw new Error(
          getLocalizedApiMessage(
            result,
            isResubmitMode
              ? "Guide profile could not be resubmitted. Please try again."
              : "Guide registration could not be submitted. Please try again.",
          ),
        );
      }

      setSubmitMessage(
        getLocalizedApiMessage(
          result,
          isResubmitMode
            ? "Guide profile resubmitted successfully."
            : "Guide registration submitted successfully.",
        ),
      );
      setIsSuccess(true);
    } catch (error) {
      setSubmitError(
        error instanceof Error
          ? error.message
          : isResubmitMode
            ? "Guide profile could not be resubmitted. Please try again."
            : "Guide registration could not be submitted. Please try again.",
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  useEffect(() => {
    if (isLoading || !isAuthenticated || !user) return;

    router.replace(user.role === "admin" ? "/admin" : "/dashboard");
  }, [isAuthenticated, isLoading, router, user]);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const shouldResubmit = params.get("resubmit") === "1";
    const uuid = params.get("uuid") || "";
    const queryEmail = params.get("email") || "";

    if (!shouldResubmit) return;

    setIsResubmitMode(true);
    setResubmitUuid(uuid);

    if (queryEmail) {
      setFormData((prev) => ({ ...prev, email: queryEmail }));
      setEmailAvailability(initialAvailabilityState);
    }
  }, []);

  useEffect(() => {
    if (!isResubmitMode || !resubmitUuid) return;

    const controller = new AbortController();

    async function fetchResubmitDetail() {
      setIsLoadingResubmit(true);
      setSubmitError("");

      try {
        const response = await apiRequest(
          apiUrl(`/website/guides/${resubmitUuid}`),
          {
            method: "GET",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
            },
            signal: controller.signal,
          },
        );
        const result =
          (await response.json()) as GuideRegistrationDetailResponse;

        if (!response.ok || result.success === false) {
          throw new Error(
            getLocalizedApiMessage(
              result,
              "Unable to fetch rejected profile details.",
            ),
          );
        }

        const detail = getDetailFromResponse(result);

        if (!detail) {
          throw new Error("Rejected profile details were not found.");
        }

        setFormData((prev) => ({
          ...prev,
          name: valueToString(detail.name).toLocaleUpperCase(),
          email: valueToString(detail.email),
          phone: valueToString(detail.phone),
          fatherName: valueToString(
            detail.father_name || getIdentityDetail(detail).father_name,
          ).toLocaleUpperCase(),
          motherName: valueToString(
            detail.mother_name || getIdentityDetail(detail).mother_name,
          ).toLocaleUpperCase(),
          dateOfBirth: valueToDateDisplay(
            detail.date_of_birth ||
              detail.dateOfBirth ||
              detail.dob ||
              getIdentityDetail(detail).date_of_birth ||
              getIdentityDetail(detail).dateOfBirth ||
              getIdentityDetail(detail).dob,
          ),
          districtUuid: valueToString(
            detail.district_uuid ||
              detail.district?.district_uuid ||
              detail.district?.uuid,
          ),
          profileImage: null,
          address: valueToString(detail.address),
          experience:
            valueToString(detail.year_of_experience) ||
            valueToString(detail.experience),
          companyName:
            valueToString(detail.company_name) ||
            valueToString(detail.companyName),
          bio: valueToString(detail.bio),
          courseUuid: valueToString(detail.course_uuid || detail.course?.uuid),
          courseLocationUuid: valueToString(
            detail.course_district_uuid ||
              detail.course_district?.uuid ||
              detail.course_location_uuid ||
              (typeof detail.course_location === "object" && detail.course_location
                ? detail.course_location.uuid
                : ""),
          ),
          languages: selectedDetailValues(
            detail.languages,
            detail.language_uuids,
          ),
          expertise: selectedDetailValues(
            detail.skills || detail.expertise,
            detail.skill_uuids,
          ),
          districts: selectedDetailValues(
            detail.locations,
            detail.location_uuids,
          ),
          password: "",
          confirmPassword: "",
          agreeTerms: false,
        }));
        setExistingProfileImage(
          valueToString(detail.profile_image_url || detail.profile_image),
        );
        const supportingDocuments = [
          ...(detail.supporting_documents || []),
          ...(detail.documents || []),
        ];
        setExistingDocuments(
          supportingDocuments.reduce<
            Record<string, ExistingRegistrationDocument>
          >((documents, document) => {
            const key = getSupportingDocumentTypeKey(document);
            const path = getSupportingDocumentPath(document);

            if (key && path) {
              documents[key] = {
                name: getSupportingDocumentName(document),
                path,
              };
            }

            return documents;
          }, {}),
        );
        setResubmitReason(
          detail.reject_reason ||
            detail.rejected_reason ||
            detail.rejection_reason ||
            "",
        );
        setEmailAvailability(initialAvailabilityState);
        setPhoneAvailability(initialAvailabilityState);
      } catch (error) {
        if (isApiRequestCanceled(error)) {
          return;
        }

        setSubmitError(
          error instanceof Error
            ? error.message
            : "Unable to fetch rejected profile details.",
        );
      } finally {
        if (!controller.signal.aborted) {
          setIsLoadingResubmit(false);
        }
      }
    }

    fetchResubmitDetail();

    return () => controller.abort();
  }, [isResubmitMode, resubmitUuid]);

  useEffect(() => {
    const email = formData.email.trim();

    if (isResubmitMode) {
      setEmailAvailability(initialAvailabilityState);
      return;
    }

    if (!email) {
      setEmailAvailability(initialAvailabilityState);
      return;
    }

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setEmailAvailability({
        status: "unavailable",
        message: "Enter a valid email address.",
      });
      return;
    }

    const controller = new AbortController();
    const timeoutId = window.setTimeout(async () => {
      setEmailAvailability({
        status: "checking",
        message: "Checking email availability...",
      });

      try {
        const response = await apiRequest(
          apiUrl("/guide-registration/checkemailexist"),
          {
            method: "POST",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ email }),
            signal: controller.signal,
          },
        );
        const result = (await response.json()) as AvailabilityCheckResponse;
        const isAvailable = getAvailabilityResult(response, result);

        setEmailAvailability({
          status: isAvailable ? "available" : "unavailable",
          message: getLocalizedApiMessage(
            result,
            isAvailable
              ? "Email is available."
              : "Email already exists or cannot be used.",
          ),
        });
      } catch (error) {
        if (isApiRequestCanceled(error)) {
          return;
        }

        setEmailAvailability({
          status: "unavailable",
          message: "Unable to check email availability. Please try again.",
        });
      }
    }, 500);

    return () => {
      window.clearTimeout(timeoutId);
      controller.abort();
    };
  }, [formData.email, isResubmitMode]);

  useEffect(() => {
    const phone = formData.phone.trim();

    if (isResubmitMode) {
      setPhoneAvailability(initialAvailabilityState);
      return;
    }

    if (!phone) {
      setPhoneAvailability(initialAvailabilityState);
      return;
    }

    if (!/^\d{10}$/.test(phone)) {
      setPhoneAvailability({
        status: "unavailable",
        message: "Enter a valid phone number.",
      });
      return;
    }

    const controller = new AbortController();
    const timeoutId = window.setTimeout(async () => {
      setPhoneAvailability({
        status: "checking",
        message: "Checking phone availability...",
      });

      try {
        const response = await apiRequest(
          apiUrl("/guide-registration/checkphoneexist"),
          {
            method: "POST",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ phone }),
            signal: controller.signal,
          },
        );
        const result = (await response.json()) as AvailabilityCheckResponse;
        const isAvailable = getAvailabilityResult(response, result);

        setPhoneAvailability({
          status: isAvailable ? "available" : "unavailable",
          message: getLocalizedApiMessage(
            result,
            isAvailable
              ? "Phone number is available."
              : "Phone number already exists or cannot be used.",
          ),
        });
      } catch (error) {
        if (isApiRequestCanceled(error)) {
          return;
        }

        setPhoneAvailability({
          status: "unavailable",
          message: "Unable to check phone availability. Please try again.",
        });
      }
    }, 500);

    return () => {
      window.clearTimeout(timeoutId);
      controller.abort();
    };
  }, [formData.phone, isResubmitMode]);

  useEffect(() => {
    const controller = new AbortController();

    async function fetchRegistrationOptions() {
      setIsLoadingRegistrationOptions(true);
      setRegistrationOptionsError("");

      try {
        const response = await apiRequest(
          apiUrl("/guide-registration/options"),
          {
            method: "GET",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
            },
            signal: controller.signal,
          },
        );

        if (!response.ok) {
          throw new Error(`Options request failed: ${response.status}`);
        }

        const result =
          (await response.json()) as GuideRegistrationOptionsResponse;

        setRegistrationOptions({
          languages: getOptionsOrFallback(
            result.data?.languages,
            fallbackRegistrationOptions.languages,
          ),
          skills: getOptionsOrFallback(
            result.data?.skills,
            fallbackRegistrationOptions.skills,
          ),
          locations: getOptionsOrFallback(
            result.data?.locations,
            fallbackRegistrationOptions.locations,
          ),
          districts: getActiveOptions(result.data?.districts),
          courses: getActiveOptions(result.data?.courses),
          courseLocations: getActiveOptions(result.data?.course_districts),
          documentTypes: getOptionArray(result.data?.document_types).filter(
            isActiveDocumentType,
          ),
        });
      } catch (error) {
        if (isApiRequestCanceled(error)) {
          return;
        }

        console.error("Failed to fetch guide registration options", error);
        setRegistrationOptionsError(
          error instanceof Error
            ? error.message
            : "Failed to load registration options.",
        );
      } finally {
        if (!controller.signal.aborted) {
          setIsLoadingRegistrationOptions(false);
        }
      }
    }

    fetchRegistrationOptions();

    return () => controller.abort();
  }, []);

  if (isLoading || isAuthenticated) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-[var(--theme-surface)]">
        <div className="h-10 w-10 animate-spin rounded-full border-4 border-[var(--theme-secondary)]/25 border-t-[var(--theme-primary)]" />
      </div>
    );
  }

  if (isLoadingResubmit) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-[var(--theme-surface)] px-4">
        <div className="rounded-3xl border border-[var(--theme-border-soft)] bg-white p-8 text-center shadow-xl">
          <div className="mx-auto mb-4 h-10 w-10 animate-spin rounded-full border-4 border-[var(--theme-secondary)]/25 border-t-[var(--theme-primary)]" />
          <p className="text-lg font-black text-foreground">
            Loading rejected profile details...
          </p>
          <p className="mt-2 text-sm text-muted-foreground">
            Please wait while we prepare your resubmit form.
          </p>
        </div>
      </div>
    );
  }

  if (isSuccess) {
    return (
      <div className="relative flex min-h-screen items-center justify-center overflow-hidden px-4 pb-32 pt-24">
        <Image
          src="https://images.unsplash.com/photo-1626621341517-bbf3d9990a23?w=1800&q=85"
          alt="Uttarakhand Mountains"
          fill
          className="object-cover"
          priority
        />
        <div className="absolute inset-0 bg-gradient-to-r from-background/92 via-background/72 to-background/40" />
        <div className="absolute inset-0 bg-gradient-to-t from-black/30 via-transparent to-white/10" />

        <Card className="relative z-10 w-full max-w-lg overflow-hidden border-border/60 bg-white/95 text-center shadow-2xl shadow-black/15 backdrop-blur-md">
          <CardContent className="p-8 sm:p-10">
            <div className="mx-auto mb-5 flex h-20 w-20 items-center justify-center rounded-full bg-[var(--theme-surface-strong)] shadow-lg shadow-[var(--theme-secondary)]/10">
              <div className="flex h-14 w-14 items-center justify-center rounded-full bg-gradient-to-r from-[var(--theme-secondary)] to-[var(--theme-accent)] text-white shadow-md shadow-[var(--theme-secondary)]/25">
                <CheckCircle2 className="h-8 w-8" />
              </div>
            </div>
            <div className="mb-4 inline-flex rounded-full border border-[var(--theme-secondary)]/25 bg-[var(--theme-surface-strong)] px-4 py-2 text-sm font-semibold text-[var(--theme-primary)] shadow-sm">
              {isResubmitMode
                ? "Profile Resubmitted"
                : t("register.applicationReceived")}
            </div>
            <h2 className="mb-3 text-3xl font-black text-foreground">
              {isResubmitMode
                ? "Profile Resubmitted Successfully!"
                : t("register.submitted")}
            </h2>
            <p className="mx-auto mb-7 max-w-md leading-7 text-muted-foreground">
              {submitMessage ||
                (isResubmitMode
                  ? "Your updated profile has been submitted again for admin verification."
                  : t("register.submittedDescription"))}
            </p>

            <div className="mb-7 grid gap-3 rounded-2xl border border-[#f4dfd1] bg-[var(--theme-surface-soft)] p-4 text-left text-sm text-muted-foreground">
              <div className="flex items-center gap-3">
                <span className="h-2.5 w-2.5 rounded-full bg-[var(--theme-secondary)]" />
                {isResubmitMode
                  ? "Your corrected profile is now pending admin review."
                  : t("register.verificationStarts")}
              </div>
              <div className="flex items-center gap-3">
                <span className="h-2.5 w-2.5 rounded-full bg-[var(--theme-secondary)]" />
                {isResubmitMode
                  ? "You can sign in after your profile is approved by admin."
                  : t("register.emailUpdates")}
              </div>
            </div>

            <div className="grid gap-3 sm:grid-cols-2">
              <Link href="/">
                <Button className="h-11 w-full rounded-full">
                  {t("register.returnHome")}
                </Button>
              </Link>
              <Link href="/auth/login">
                <Button
                  variant="outline"
                  className="h-11 w-full rounded-full border-[var(--theme-secondary)]/30 text-[var(--theme-primary)] hover:bg-[var(--theme-surface-strong)] hover:text-[var(--theme-primary)]"
                >
                  {t("common.signIn")}
                </Button>
              </Link>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="relative min-h-screen overflow-hidden pb-24 pt-20 lg:pb-28">
      <Image
        src="https://images.unsplash.com/photo-1626621341517-bbf3d9990a23?w=1800&q=85"
        alt="Uttarakhand Mountains"
        fill
        className="object-cover"
        priority
      />
      <div className="absolute inset-0 bg-gradient-to-r from-background/92 via-background/70 to-background/35" />
      <div className="absolute inset-0 bg-gradient-to-t from-black/30 via-transparent to-white/10" />

      <div className="relative z-10 mx-auto flex w-full max-w-7xl items-center justify-center p-6 lg:p-10">
        <div className="w-full overflow-hidden rounded-3xl bg-white shadow-2xl shadow-black/10">
          <section className="bg-white p-6 sm:p-8 lg:p-10">
            {/* Header */}
            <div className="mb-6">
              <div className="mb-4 inline-flex rounded-full border border-[var(--theme-secondary)]/25 bg-[var(--theme-surface-strong)] px-4 py-2 text-sm font-semibold text-[var(--theme-primary)] shadow-sm">
                {t("common.becomeGuide")}
              </div>
              <h1 className="text-3xl font-black text-foreground">
                {isResubmitMode
                  ? "Resubmit Guide Profile"
                  : t("register.title")}
              </h1>
              <p className="mt-2 max-w-2xl text-muted-foreground">
                {isResubmitMode
                  ? "Update the required details and submit your profile again for admin verification."
                  : t("register.subtitle")}
              </p>
            </div>

            {isResubmitMode && resubmitReason && (
              <Alert className="mb-6 border-amber-200 bg-amber-50 text-amber-800">
                <AlertTriangle className="h-4 w-4 text-amber-600" />
                <AlertDescription>
                  <span className="font-black">Rejected Reason:</span>{" "}
                  <span className="font-medium">{resubmitReason}</span>
                </AlertDescription>
              </Alert>
            )}

            {/* Progress Steps */}
            <div className="mb-6">
              <div className="flex items-start justify-between rounded-2xl border border-border/60 bg-[var(--theme-surface-soft)] p-3 shadow-sm">
                {steps.map((step, index) => (
                  <div key={step.id} className="flex flex-1 items-start">
                    <div className="flex flex-col items-center">
                      <div
                        className={cn(
                          "flex h-11 w-11 items-center justify-center rounded-full border transition-all",
                          currentStep > step.id
                            ? "border-[var(--theme-secondary)] bg-gradient-to-r from-[var(--theme-secondary)] to-[var(--theme-accent)] text-white shadow-md shadow-[var(--theme-secondary)]/20"
                            : currentStep === step.id
                              ? "border-[var(--theme-secondary)] bg-[var(--theme-surface-strong)] text-[var(--theme-primary)]"
                              : "border-border bg-white text-muted-foreground",
                        )}
                      >
                        {currentStep > step.id ? (
                          <CheckCircle2 className="h-5 w-5" />
                        ) : (
                          <span className="text-sm font-medium">{step.id}</span>
                        )}
                      </div>
                      <div className="mt-2 hidden text-center sm:block">
                        <p
                          className={cn(
                            "text-sm font-medium",
                            currentStep >= step.id
                              ? "text-foreground"
                              : "text-muted-foreground",
                          )}
                        >
                          {t(step.title)}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {t(step.description)}
                        </p>
                      </div>
                    </div>
                    {index < steps.length - 1 && (
                      <div
                        className={cn(
                          "mt-5 h-px flex-1 border-t border-dashed",
                          currentStep > step.id
                            ? "border-[var(--theme-secondary)]"
                            : "border-border",
                        )}
                      />
                    )}
                  </div>
                ))}
              </div>
            </div>

            {/* Form Area */}
            <div className="rounded-2xl border border-border/60 bg-white p-4 shadow-sm sm:p-6">
              <div className="mb-5">
                <h2 className="text-2xl font-black text-foreground">
                  {t(steps[currentStep - 1].title)}
                </h2>
                <p className="mt-1 text-sm text-muted-foreground">
                  {currentStep === 1 && t("register.tellAboutYourself")}
                  {currentStep === 2 && t("register.shareProfessional")}
                  {currentStep === 3 && t("register.selectAreas")}
                  {currentStep === 4 && t("register.documentRequirementsHelp")}
                  {currentStep === 5 &&
                    (isResubmitMode
                      ? "Leave password blank if you do not want to update it."
                      : t("register.createSecureAccess"))}
                  {currentStep === 6 && t("register.reviewSubmit")}
                </p>
              </div>
              {/* Step 1: Personal Info */}
              {currentStep === 1 && (
                <div className="space-y-6">
                  <div className="rounded-2xl border border-[#acd6ff] bg-[#eff6ff]/95 p-4 text-[#002b7f] shadow-[0_8px_20px_rgba(0,141,204,0.12)]">
                    <div className="grid gap-3 text-xs leading-5 lg:grid-cols-[max-content_1fr_1fr] lg:items-center lg:gap-x-2">
                      <div className="flex items-center gap-2 font-black text-[#00194f]">
                        <span className="flex h-5 w-5 items-center justify-center rounded-full border border-[#84bdff] bg-white text-[var(--theme-primary)]">
                          <Info className="h-3.5 w-3.5" />
                        </span>
                        <span>Guidelines</span>
                      </div>
                      <div className="grid gap-1 border-t border-[#c7dcff] pt-3 lg:border-l lg:border-t-0 lg:pl-2 lg:pt-0">
                        <PersonalGuideline
                          text={t("register.photoRequirements")}
                        />
                        <PersonalGuideline
                          text={t("register.dobRequirement")}
                        />
                      </div>
                      <div className="grid gap-1 border-t border-[#c7dcff] pt-3 lg:border-l lg:border-t-0 lg:pl-2 lg:pt-0">
                        <PersonalGuideline
                          text={t("register.textFormatting")}
                        />
                        <PersonalGuideline
                          text={t("register.mobileAddressRequirement")}
                        />
                      </div>
                    </div>
                  </div>

                  <div className="rounded-2xl border border-border/60 bg-white p-4 shadow-sm">
                    <div className="grid gap-6 lg:grid-cols-[260px_minmax(0,1fr)] lg:items-start">
                      <div className="rounded-2xl border border-[var(--theme-border-strong)] bg-white p-3 shadow-sm">
                        <Label
                          htmlFor="profileImage"
                          className="text-sm font-semibold text-foreground"
                        >
                          {t("register.profileImage")} *
                        </Label>
                        <div className="mt-3 flex h-[312px] max-h-[58vh] min-h-64 items-center justify-center overflow-hidden rounded-lg border border-border bg-[var(--theme-surface-soft)] text-[var(--theme-primary)]">
                          {profileImageSource ? (
                            <img
                              src={profileImageSource}
                              alt={t("register.profileImage")}
                              className="h-full w-full object-cover"
                            />
                          ) : (
                            <div className="flex flex-col items-center gap-2 text-center text-sm font-semibold text-[var(--theme-primary)]">
                              <Camera className="h-9 w-9" />
                              <span>{profileImageLabel}</span>
                            </div>
                          )}
                        </div>
                        <input
                          ref={profileImageInputRef}
                          id="profileImage"
                          type="file"
                          accept="image/jpeg,image/png"
                          className="hidden"
                          onChange={(event) =>
                            handleProfileImageChange(event.target.files?.[0])
                          }
                        />
                        <div className="mt-3 grid grid-cols-2 gap-2">
                          <Button
                            type="button"
                            variant="outline"
                            onClick={() =>
                              profileImageInputRef.current?.click()
                            }
                            className={cn(
                              "h-10 border-[var(--theme-secondary)]/35 text-[var(--theme-primary)] hover:bg-[var(--theme-surface-strong)] hover:text-[var(--theme-primary)]",
                              !formData.profileImage && "col-span-2",
                            )}
                          >
                            <Upload className="h-4 w-4" />
                            {t("register.upload")}
                          </Button>
                          {formData.profileImage && (
                            <Button
                              type="button"
                              variant="outline"
                              onClick={clearProfileImageSelection}
                              className="h-10 border-red-200 text-red-600 hover:border-red-300 hover:bg-red-50 hover:text-red-700"
                            >
                              <Trash2 className="h-4 w-4" />
                              Remove
                            </Button>
                          )}
                        </div>
                        {hasProfileImage && (
                          <p className="mt-2 truncate text-xs font-semibold text-muted-foreground">
                            {profileImageLabel}
                          </p>
                        )}
                        {profileImageError && (
                          <p className="mt-2 text-sm font-medium text-destructive">
                            {profileImageError}
                          </p>
                        )}
                      </div>

                      <div className="grid gap-5">
                        <div className="grid gap-4 sm:grid-cols-2">
                          <div className="space-y-2">
                            <Label
                              htmlFor="name"
                              className="text-sm font-semibold text-foreground"
                            >
                              {t("register.fullName")} *
                            </Label>
                            <Input
                              id="name"
                              placeholder={t("register.fullNamePlaceholder")}
                              value={formData.name}
                              onChange={(e) =>
                                updateField(
                                  "name",
                                  e.target.value.toLocaleUpperCase(),
                                )
                              }
                              className="h-11 w-full rounded-lg bg-white"
                            />
                          </div>
                          <div className="space-y-2">
                            <Label
                              htmlFor="email"
                              className="text-sm font-semibold text-foreground"
                            >
                              {t("register.email")} *
                            </Label>
                            <Input
                              id="email"
                              type="email"
                              placeholder={t("auth.emailPlaceholder")}
                              value={formData.email}
                              onChange={(e) =>
                                updateField("email", e.target.value)
                              }
                              readOnly={isResubmitMode}
                              className={cn(
                                "h-11 rounded-lg bg-white",
                                isResubmitMode &&
                                  "cursor-not-allowed bg-[var(--theme-surface-soft)] text-muted-foreground",
                              )}
                            />
                            {emailAvailability.message && (
                              <p
                                className={getAvailabilityClassName(
                                  emailAvailability.status,
                                )}
                              >
                                {emailAvailability.status === "checking" && (
                                  <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                )}
                                {emailAvailability.status === "available" && (
                                  <CheckCircle2 className="h-3.5 w-3.5" />
                                )}
                                {emailAvailability.message}
                              </p>
                            )}
                          </div>
                        </div>

                        <div className="grid gap-4 sm:grid-cols-2">
                          <div className="space-y-2">
                            <Label
                              htmlFor="fatherName"
                              className="text-sm font-semibold text-foreground"
                            >
                              {t("register.fatherName")} *
                            </Label>
                            <Input
                              id="fatherName"
                              placeholder={t("register.fatherNamePlaceholder")}
                              value={formData.fatherName}
                              onChange={(e) =>
                                updateField(
                                  "fatherName",
                                  e.target.value.toLocaleUpperCase(),
                                )
                              }
                              className="h-11 w-full rounded-lg bg-white"
                            />
                          </div>
                          <div className="space-y-2">
                            <Label
                              htmlFor="motherName"
                              className="text-sm font-semibold text-foreground"
                            >
                              {t("register.motherName")} *
                            </Label>
                            <Input
                              id="motherName"
                              placeholder={t("register.motherNamePlaceholder")}
                              value={formData.motherName}
                              onChange={(e) =>
                                updateField(
                                  "motherName",
                                  e.target.value.toLocaleUpperCase(),
                                )
                              }
                              className="h-11 w-full rounded-lg bg-white"
                            />
                          </div>
                        </div>

                        <div className="grid gap-4 sm:grid-cols-2">
                          <div className="space-y-2">
                            <Label
                              htmlFor="phone"
                              className="text-sm font-semibold text-foreground"
                            >
                              {isResubmitMode
                                ? "Contact Number"
                                : t("register.phoneNumber")}{" "}
                              *
                            </Label>
                            <div className="flex h-11 overflow-hidden rounded-lg border border-input bg-white focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50">
                              <span className="flex w-14 shrink-0 items-center justify-center border-r border-input text-sm font-black text-[var(--theme-accent)]">
                                +91
                              </span>
                              <Input
                                id="phone"
                                placeholder={t("register.phonePlaceholder")}
                                value={formData.phone}
                                inputMode="numeric"
                                maxLength={10}
                                onChange={(e) =>
                                  updateField(
                                    "phone",
                                    e.target.value
                                      .replace(/\D/g, "")
                                      .slice(0, 10),
                                  )
                                }
                                readOnly={isResubmitMode}
                                className={cn(
                                  "h-full rounded-none border-0 bg-white shadow-none focus-visible:ring-0",
                                  isResubmitMode &&
                                    "cursor-not-allowed bg-[var(--theme-surface-soft)] text-muted-foreground",
                                )}
                              />
                            </div>
                            {phoneAvailability.message && (
                              <p
                                className={getAvailabilityClassName(
                                  phoneAvailability.status,
                                )}
                              >
                                {phoneAvailability.status === "checking" && (
                                  <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                )}
                                {phoneAvailability.status === "available" && (
                                  <CheckCircle2 className="h-3.5 w-3.5" />
                                )}
                                {phoneAvailability.message}
                              </p>
                            )}
                          </div>
                          <div className="space-y-2">
                            <Label
                              htmlFor="dateOfBirth"
                              className="text-sm font-semibold text-foreground"
                            >
                              {t("register.dateOfBirth")} *
                            </Label>
                            <DatePickerInput
                              id="dateOfBirth"
                              value={dateDisplayToApi(formData.dateOfBirth)}
                              onValueChange={(value) =>
                                updateField(
                                  "dateOfBirth",
                                  valueToDateDisplay(value),
                                )
                              }
                              className="h-11 w-full rounded-lg bg-white"
                              maxDate={new Date()}
                              required
                            />
                          </div>
                        </div>

                        <div className="space-y-2">
                          <Label
                            htmlFor="district"
                            className="text-sm font-semibold text-foreground"
                          >
                            Choose District *
                          </Label>
                          <Select
                            value={formData.districtUuid}
                            onValueChange={(value) =>
                              updateField("districtUuid", value)
                            }
                          >
                            <SelectTrigger
                              id="district"
                              className="!h-11 min-h-11 w-full rounded-lg bg-white text-sm font-medium shadow-sm"
                            >
                              <div className="flex min-w-0 flex-1 items-center gap-2 pr-7">
                                <MapPin className="h-4 w-4 shrink-0 text-[var(--theme-primary)]" />
                                <SelectValue placeholder="Select district" />
                              </div>
                            </SelectTrigger>
                            <SelectContent className="w-[var(--radix-select-trigger-width)]">
                              {registrationOptions.districts.length ? (
                                registrationOptions.districts.map(
                                  (option, index) => {
                                    const optionValue = getOptionValue(option);

                                    return (
                                      <SelectItem
                                        key={`${optionValue}-${index}`}
                                        value={optionValue}
                                      >
                                        {displayRegistrationOption(
                                          option,
                                          displayDistrict,
                                        )}
                                      </SelectItem>
                                    );
                                  },
                                )
                              ) : (
                                <div className="px-3 py-2 text-sm font-medium text-muted-foreground">
                                  No districts found
                                </div>
                              )}
                            </SelectContent>
                          </Select>
                        </div>

                        <div className="space-y-2">
                          <Label
                            htmlFor="address"
                            className="text-sm font-semibold text-foreground"
                          >
                            {t("register.address")} *
                          </Label>
                          <Textarea
                            id="address"
                            placeholder={t("register.addressPlaceholder")}
                            value={formData.address}
                            onChange={(e) =>
                              updateField("address", e.target.value)
                            }
                            rows={3}
                            className="min-h-[106px] rounded-lg bg-white"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* Step 2: Professional */}
              {currentStep === 2 && (
                <div className="space-y-5">
                  <div className="grid sm:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="companyName">
                        Firm/Company/Agency Name
                      </Label>
                      <Input
                        id="companyName"
                        placeholder={t("register.companyNamePlaceholder")}
                        value={formData.companyName}
                        onChange={(e) =>
                          updateField("companyName", e.target.value)
                        }
                        className="h-11 w-full rounded-lg bg-white"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="experience">
                        {t("register.experienceYears")} *
                      </Label>
                      <Input
                        id="experience"
                        type="number"
                        placeholder={t("register.experiencePlaceholder")}
                        value={formData.experience}
                        onChange={(e) =>
                          updateField("experience", e.target.value)
                        }
                        className="h-11 w-full rounded-lg bg-white"
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="bio">{t("register.bio")} *</Label>
                    <Textarea
                      id="bio"
                      placeholder={t("register.bioPlaceholder")}
                      value={formData.bio}
                      onChange={(e) => updateField("bio", e.target.value)}
                      rows={4}
                      className="min-h-[118px] rounded-lg bg-white"
                    />
                  </div>

                  <div className="grid gap-4 sm:grid-cols-2">
                    <div className="space-y-2">
                      <Label htmlFor="courseUuid">Course *</Label>
                      <Select
                        value={formData.courseUuid}
                        onValueChange={(value) => {
                          updateField("courseUuid", value);
                          updateField("courseLocationUuid", "");
                        }}
                        disabled={
                          isLoadingRegistrationOptions ||
                          registrationOptions.courses.length === 0
                        }
                      >
                        <SelectTrigger
                          id="courseUuid"
                          className="h-11 w-full rounded-lg bg-white"
                        >
                          <SelectValue
                            placeholder={
                              isLoadingRegistrationOptions
                                ? "Loading courses..."
                                : registrationOptions.courses.length
                                  ? "Select course"
                                  : "No courses available"
                            }
                          />
                        </SelectTrigger>
                        <SelectContent>
                          {registrationOptions.courses.map((option, index) => {
                            const optionValue = getOptionValue(option);

                            return (
                              <SelectItem
                                key={`${optionValue}-${index}`}
                                value={optionValue}
                              >
                                {displayRegistrationOption(option, (value) => value)}
                              </SelectItem>
                            );
                          })}
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="courseLocationUuid">Course District *</Label>
                      <Select
                        value={formData.courseLocationUuid}
                        onValueChange={(value) =>
                          updateField("courseLocationUuid", value)
                        }
                        disabled={
                          isLoadingRegistrationOptions ||
                          !formData.courseUuid ||
                          courseLocationOptions.length === 0
                        }
                      >
                        <SelectTrigger
                          id="courseLocationUuid"
                          className="h-11 w-full rounded-lg bg-white"
                        >
                          <SelectValue
                            placeholder={
                              isLoadingRegistrationOptions
                                ? "Loading course districts..."
                                : !formData.courseUuid
                                  ? "Select course first"
                                  : courseLocationOptions.length
                                    ? "Select course district"
                                    : "No course districts available"
                            }
                          />
                        </SelectTrigger>
                        <SelectContent>
                          {courseLocationOptions.map((option, index) => {
                            const optionValue = getOptionValue(option);

                            return (
                              <SelectItem
                                key={`${optionValue}-${index}`}
                                value={optionValue}
                              >
                                {displayRegistrationOption(option, displayDistrict)}
                              </SelectItem>
                            );
                          })}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>

                  <div className="space-y-3">
                    <Label>{t("register.languagesSpoken")} *</Label>
                    <div className="flex flex-wrap gap-2">
                      {registrationOptions.languages.map((option, index) => {
                        const optionValue = getOptionValue(option);
                        const isDisabled = isSelectionLimitReached(
                          "languages",
                          optionValue,
                        );

                        return (
                          <Button
                            key={`${optionValue}-${index}`}
                            disabled={isDisabled}
                            type="button"
                            variant={
                              formData.languages.includes(optionValue)
                                ? "default"
                                : "outline"
                            }
                            size="sm"
                            onClick={() =>
                              toggleArrayItem("languages", optionValue)
                            }
                          >
                            {displayRegistrationOption(option, displayLanguage)}
                          </Button>
                        );
                      })}
                    </div>
                  </div>

                  <div className="space-y-3">
                    <Label>{t("register.areasExpertise")} *</Label>
                    <div className="flex flex-wrap gap-2">
                      {registrationOptions.skills.map((option, index) => {
                        const optionValue = getOptionValue(option);
                        const isDisabled = isSelectionLimitReached(
                          "expertise",
                          optionValue,
                        );

                        return (
                          <Button
                            key={`${optionValue}-${index}`}
                            disabled={isDisabled}
                            type="button"
                            variant={
                              formData.expertise.includes(optionValue)
                                ? "default"
                                : "outline"
                            }
                            size="sm"
                            onClick={() =>
                              toggleArrayItem("expertise", optionValue)
                            }
                          >
                            {displayRegistrationOption(
                              option,
                              displayExpertise,
                            )}
                          </Button>
                        );
                      })}
                    </div>
                  </div>
                </div>
              )}

              {/* Step 3: Service Locations */}
              {currentStep === 3 && (
                <div className="space-y-3.5">
                  <Alert>
                    <AlertDescription>
                      {t("register.selectDistrictsHelp")}
                    </AlertDescription>
                  </Alert>
                  <div className="grid sm:grid-cols-2 gap-3">
                    {registrationOptions.locations.map((option, index) => {
                      const optionValue = getOptionValue(option);
                      const isDisabled = isSelectionLimitReached(
                        "districts",
                        optionValue,
                      );

                      return (
                        <div
                          key={`${optionValue}-${index}`}
                          className={cn(
                            "flex items-center gap-3 p-3 rounded-lg border transition-colors",
                            isDisabled
                              ? "cursor-not-allowed opacity-50"
                              : "cursor-pointer",
                            formData.districts.includes(optionValue)
                              ? "border-primary bg-primary/5"
                              : "border-border hover:border-primary/50",
                          )}
                          onClick={() => {
                            if (!isDisabled) {
                              toggleArrayItem("districts", optionValue);
                            }
                          }}
                        >
                          <Checkbox
                            checked={formData.districts.includes(optionValue)}
                            onClick={(event) => event.stopPropagation()}
                            disabled={isDisabled}
                            onCheckedChange={() =>
                              toggleArrayItem("districts", optionValue)
                            }
                          />
                          <span className="text-sm">
                            {displayRegistrationOption(option, displayDistrict)}
                          </span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {/* Step 4: Documents */}
              {currentStep === 4 && (
                <div className="rounded-3xl border border-[var(--theme-border)] bg-white p-4 sm:p-5">
                  <h3 className="mb-2 font-black text-foreground">
                    {t("register.documentRequirements")}
                  </h3>
                  <p className="text-sm leading-6 text-muted-foreground">
                    {t("register.documentQualityHelp")}
                  </p>

                  <div className="mt-4 grid grid-cols-2 gap-3 md:grid-cols-4">
                    <DocumentQualityTip label={t("register.clear")} ok />
                    <DocumentQualityTip
                      label={t("register.noGlare")}
                      ok={false}
                    />
                    <DocumentQualityTip
                      label={t("register.notCropped")}
                      ok={false}
                    />
                    <DocumentQualityTip label={t("register.allCorners")} ok />
                  </div>

                  <div className="mt-5 space-y-4">
                    {isLoadingRegistrationOptions && (
                      <div className="rounded-2xl bg-gray-50 p-4 text-sm font-semibold text-muted-foreground">
                        Loading document requirements...
                      </div>
                    )}
                    {registrationOptionsError && (
                      <div className="rounded-2xl bg-red-50 p-4 text-sm font-semibold text-red-700">
                        {registrationOptionsError}
                      </div>
                    )}
                    {!isLoadingRegistrationOptions &&
                      !registrationOptionsError &&
                      activeDocumentTypes.length === 0 && (
                        <div className="rounded-2xl bg-gray-50 p-4 text-sm font-semibold text-muted-foreground">
                          {t("register.noDocumentRequirements")}
                        </div>
                      )}{" "}
                    {!isLoadingRegistrationOptions &&
                      !registrationOptionsError &&
                      activeDocumentTypes.map((documentType, index) => {
                        const key = getDocumentTypeKey(documentType);

                        return (
                          <RegistrationDocumentRow
                            key={key}
                            index={index + 1}
                            documentType={documentType}
                            displayTitle={displayRegistrationOption(
                              documentType,
                              (value) => value,
                            )}
                            file={documentUploads[key]}
                            existingDocument={existingDocuments[key]}
                            error={documentErrors[key]}
                            onUpload={(file) =>
                              handleDocumentUpload(documentType, file)
                            }
                            onPreview={() =>
                              handleDocumentPreview(documentType)
                            }
                            onDelete={() => handleDocumentDelete(documentType)}
                            uploadLabel={t("register.upload")}
                            viewLabel={t("register.view")}
                            deleteLabel={t("register.delete")}
                          />
                        );
                      })}
                  </div>
                </div>
              )}

              {/* Step 5: Password */}
              {currentStep === 5 && (
                <div className="grid gap-5 lg:grid-cols-2 lg:items-start">
                  <div className="space-y-3">
                    <div className="space-y-2">
                      <Label htmlFor="password">
                        {t("auth.password")}{" "}
                        {isResubmitMode ? "(Optional)" : "*"}
                      </Label>
                      <div className="relative">
                        <Input
                          id="password"
                          type={showPassword ? "text" : "password"}
                          placeholder={t("register.createPassword")}
                          value={formData.password}
                          onChange={(e) =>
                            updateField("password", e.target.value)
                          }
                          className="h-11 rounded-lg bg-white pr-11"
                        />
                        <button
                          type="button"
                          onClick={() => setShowPassword((value) => !value)}
                          className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-foreground"
                          aria-label={
                            showPassword
                              ? t("register.hidePassword")
                              : t("register.showPassword")
                          }
                        >
                          {showPassword ? (
                            <EyeOff className="h-4 w-4" />
                          ) : (
                            <Eye className="h-4 w-4" />
                          )}
                        </button>
                      </div>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="confirmPassword">
                        {t("register.confirmPassword")}{" "}
                        {isResubmitMode ? "(Optional)" : "*"}
                      </Label>
                      <div className="relative">
                        <Input
                          id="confirmPassword"
                          type={showConfirmPassword ? "text" : "password"}
                          placeholder={t("register.confirmPasswordPlaceholder")}
                          value={formData.confirmPassword}
                          onChange={(e) =>
                            updateField("confirmPassword", e.target.value)
                          }
                          className="h-11 rounded-lg bg-white pr-11"
                        />
                        <button
                          type="button"
                          onClick={() =>
                            setShowConfirmPassword((value) => !value)
                          }
                          className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-foreground"
                          aria-label={
                            showConfirmPassword
                              ? t("register.hideConfirmPassword")
                              : t("register.showConfirmPassword")
                          }
                        >
                          {showConfirmPassword ? (
                            <EyeOff className="h-4 w-4" />
                          ) : (
                            <Eye className="h-4 w-4" />
                          )}
                        </button>
                      </div>
                    </div>

                    <div className="min-h-5">
                      {formData.password &&
                        formData.confirmPassword &&
                        formData.password !== formData.confirmPassword && (
                          <p className="text-sm font-medium text-destructive">
                            {t("register.passwordMismatch")}
                          </p>
                        )}
                    </div>
                  </div>

                  <div className="rounded-2xl border border-[#f4dfd1] bg-[var(--theme-surface-soft)] p-4 shadow-sm">
                    <p className="mb-3 text-sm font-semibold text-foreground">
                      {t("register.passwordFormat")}
                    </p>
                    <div className="space-y-3 text-sm text-muted-foreground">
                      {[
                        {
                          label: t("register.ruleLength"),
                          passed: passwordRules.length,
                        },
                        {
                          label: t("register.ruleUppercase"),
                          passed: passwordRules.uppercase,
                        },
                        {
                          label: t("register.ruleNumber"),
                          passed: passwordRules.number,
                        },
                        {
                          label: t("register.ruleSpecial"),
                          passed: passwordRules.special,
                        },
                      ].map((rule) => (
                        <div
                          key={rule.label}
                          className="flex items-center gap-3"
                        >
                          <span
                            className={cn(
                              "h-3 w-3 rounded-full",
                              rule.passed
                                ? "bg-[var(--theme-secondary)]"
                                : "bg-muted-foreground/30",
                            )}
                          />
                          <span
                            className={cn(
                              rule.passed && "font-medium text-foreground",
                            )}
                          >
                            {rule.label}
                          </span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {/* Step 6: Review */}
              {currentStep === 6 && (
                <div className="space-y-5">
                  <div className="space-y-4">
                    <div className="p-4 rounded-lg bg-muted/50">
                      <h4 className="font-medium text-foreground mb-2">
                        {t("register.personalInformation")}
                      </h4>
                      <div className="mb-4 flex flex-col gap-3 rounded-lg bg-white p-3 sm:flex-row sm:items-center">
                        <div className="h-24 w-20 shrink-0 overflow-hidden rounded-lg border border-border bg-[var(--theme-surface-soft)]">
                          {profileImageSource ? (
                            <img
                              src={profileImageSource}
                              alt={t("register.profileImage")}
                              className="h-full w-full object-cover"
                            />
                          ) : (
                            <div className="flex h-full w-full items-center justify-center text-[var(--theme-primary)]">
                              <Camera className="h-6 w-6" />
                            </div>
                          )}
                        </div>
                        <div className="min-w-0 flex-1">
                          <p className="text-sm font-medium text-foreground">
                            {t("register.profileImage")}
                          </p>
                          <p className="mt-1 truncate text-xs font-semibold text-muted-foreground">
                            {profileImageLabel}
                          </p>
                        </div>
                        {profileImageSource && (
                          <Button
                            type="button"
                            size="sm"
                            variant="outline"
                            onClick={() =>
                              window.open(
                                profileImageSource,
                                "_blank",
                                "noopener,noreferrer",
                              )
                            }
                            className="h-9 rounded-lg bg-white text-[var(--theme-primary)]"
                          >
                            <Eye className="h-4 w-4" />
                            {t("register.view")}
                          </Button>
                        )}
                      </div>
                      <div className="grid sm:grid-cols-2 gap-2 text-sm">
                        <p>
                          <span className="text-muted-foreground">
                            {t("register.name")}:
                          </span>{" "}
                          {formData.name}
                        </p>
                        <p>
                          <span className="text-muted-foreground">
                            {t("register.email")}:
                          </span>{" "}
                          {formData.email}
                        </p>
                        <p>
                          <span className="text-muted-foreground">
                            {t("register.fatherName")}:
                          </span>{" "}
                          {formData.fatherName}
                        </p>
                        <p>
                          <span className="text-muted-foreground">
                            {t("register.motherName")}:
                          </span>{" "}
                          {formData.motherName}
                        </p>
                        <p>
                          <span className="text-muted-foreground">
                            {t("register.dateOfBirth")}:
                          </span>{" "}
                          {formData.dateOfBirth}
                        </p>
                        <p>
                          <span className="text-muted-foreground">
                            {t("register.phone")}:
                          </span>{" "}
                          {formData.phone}
                        </p>
                        <p>
                          <span className="text-muted-foreground">
                            District:
                          </span>{" "}
                          {findSelectedOptions(
                            [formData.districtUuid],
                            registrationOptions.districts,
                          )
                            .map((option) =>
                              displayRegistrationOption(
                                option,
                                displayDistrict,
                              ),
                            )
                            .join(", ")}
                        </p>
                        <p>
                          <span className="text-muted-foreground">
                            {t("register.address")}:
                          </span>{" "}
                          {formData.address}
                        </p>
                      </div>
                    </div>

                    <div className="p-4 rounded-lg bg-muted/50">
                      <h4 className="font-medium text-foreground mb-2">
                        {t("register.professionalDetails")}
                      </h4>
                      <div className="grid sm:grid-cols-2 gap-2 text-sm">
                        <p>
                          <span className="text-muted-foreground">
                            {t("guide.experience")}:
                          </span>{" "}
                          {formData.experience} {t("register.years")}
                        </p>
                        <p>
                          <span className="text-muted-foreground">
                            {t("register.companyName")}:
                          </span>{" "}
                          {formData.companyName || t("register.notSet")}
                        </p>
                        <p>
                          <span className="text-muted-foreground">
                            Course:
                          </span>{" "}
                          {findSelectedOptions(
                            [formData.courseUuid],
                            registrationOptions.courses,
                          )
                            .map((option) =>
                              displayRegistrationOption(option, (value) => value),
                            )
                            .join(", ")}
                        </p>
                        <p>
                          <span className="text-muted-foreground">
                            Course District:
                          </span>{" "}
                          {findSelectedOptions(
                            [formData.courseLocationUuid],
                            courseLocationOptions,
                          )
                            .map((option) =>
                              displayRegistrationOption(option, displayDistrict),
                            )
                            .join(", ")}
                        </p>
                        <p>
                          <span className="text-muted-foreground">
                            {t("register.languages")}:
                          </span>{" "}
                          {findSelectedOptions(
                            formData.languages,
                            registrationOptions.languages,
                          )
                            .map((option) =>
                              displayRegistrationOption(
                                option,
                                displayLanguage,
                              ),
                            )
                            .join(", ")}
                        </p>
                        <p>
                          <span className="text-muted-foreground">
                            {t("register.expertise")}:
                          </span>{" "}
                          {findSelectedOptions(
                            formData.expertise,
                            registrationOptions.skills,
                          )
                            .map((option) =>
                              displayRegistrationOption(
                                option,
                                displayExpertise,
                              ),
                            )
                            .join(", ")}
                        </p>
                      </div>
                    </div>

                    <div className="p-4 rounded-lg bg-muted/50">
                      <h4 className="font-medium text-foreground mb-2">
                        {t("register.areasOperation")}
                      </h4>
                      <p className="text-sm">
                        {findSelectedOptions(
                          formData.districts,
                          registrationOptions.locations,
                        )
                          .map((option) =>
                            displayRegistrationOption(option, displayDistrict),
                          )
                          .join(", ")}
                      </p>
                    </div>

                    <div className="rounded-lg bg-muted/50 p-4">
                      <h4 className="mb-3 font-medium text-foreground">
                        {t("register.documents")}
                      </h4>
                      <div className="grid gap-2 sm:grid-cols-2">
                        {activeDocumentTypes.map((documentType) => {
                          const key = getDocumentTypeKey(documentType);
                          const fileName =
                            documentUploads[key]?.name ||
                            existingDocuments[key]?.name;

                          if (!fileName) return null;

                          return (
                            <div
                              key={key}
                              className="flex min-w-0 items-center gap-2 rounded-lg bg-white p-2 text-sm"
                            >
                              <FileText className="h-4 w-4 shrink-0 text-[var(--theme-primary)]" />
                              <span className="min-w-0 truncate">
                                <span className="font-medium">
                                  {displayRegistrationOption(
                                    documentType,
                                    (value) => value,
                                  )}
                                  :
                                </span>{" "}
                                {fileName}
                              </span>
                              <Button
                                type="button"
                                size="icon-sm"
                                variant="outline"
                                onClick={() =>
                                  handleDocumentPreview(documentType)
                                }
                                className="ml-auto h-8 w-8 shrink-0 rounded-lg bg-white text-[var(--theme-primary)]"
                                aria-label={`${t("register.view")} ${fileName}`}
                                title={t("register.view")}
                              >
                                <Eye className="h-4 w-4" />
                              </Button>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  </div>

                  <div className="flex items-start gap-3 p-4 rounded-lg border border-border">
                    <Checkbox
                      id="terms"
                      checked={formData.agreeTerms}
                      onCheckedChange={(checked) =>
                        updateField("agreeTerms", checked as boolean)
                      }
                    />
                    <label
                      htmlFor="terms"
                      className="text-sm text-muted-foreground cursor-pointer"
                    >
                      {t("register.termsAgreement")}
                    </label>
                  </div>
                </div>
              )}

              {submitError && (
                <Alert className="mt-5 border-destructive/40 bg-destructive/5 text-destructive">
                  <AlertDescription>
                    <div className="space-y-3">
                      <p className="font-medium">{submitError}</p>

                      {submitValidationMessages.length > 0 && (
                        <ul className="list-disc space-y-1 pl-5">
                          {submitValidationMessages.map((message, index) => (
                            <li key={`${message}-${index}`}>{message}</li>
                          ))}
                        </ul>
                      )}
                    </div>
                  </AlertDescription>
                </Alert>
              )}

              {/* Navigation Buttons */}
              <div className="mt-6 flex justify-between border-t border-border pt-5">
                <Button
                  type="button"
                  variant="outline"
                  onClick={handleBack}
                  disabled={currentStep === 1}
                  className="rounded-full border-[var(--theme-secondary)]/30 px-5 text-[var(--theme-primary)] hover:bg-[var(--theme-surface-strong)] hover:text-[var(--theme-primary)]"
                >
                  <ArrowLeft className="h-4 w-4 mr-2" />
                  {t("register.back")}
                </Button>

                {currentStep < 6 ? (
                  <Button
                    type="button"
                    onClick={handleNext}
                    disabled={!canProceed()}
                    className="rounded-full px-6"
                  >
                    {t("register.next")}
                    <ArrowRight className="h-4 w-4 ml-2" />
                  </Button>
                ) : (
                  <Button
                    type="button"
                    onClick={handleSubmit}
                    disabled={!canProceed() || isSubmitting}
                    className={cn(
                      "rounded-full px-6",
                      isResubmitMode &&
                        "bg-gradient-to-r from-[var(--theme-secondary)] to-[var(--theme-accent)] font-black text-white shadow-lg shadow-[var(--theme-secondary)]/25 hover:from-[var(--theme-primary)] hover:to-[var(--theme-primary-dark)]",
                    )}
                  >
                    {isSubmitting ? (
                      <>
                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                        {t("register.submitting")}
                      </>
                    ) : (
                      <>
                        {isResubmitMode && <Edit className="mr-2 h-4 w-4" />}
                        {isResubmitMode
                          ? "Resubmit Profile"
                          : t("register.submitApplication")}
                      </>
                    )}
                  </Button>
                )}
              </div>
            </div>

            <p className="mt-6 text-center text-sm text-muted-foreground">
              {t("register.alreadyRegistered")}{" "}
              <Link
                href="/auth/login"
                className="font-medium text-[var(--theme-primary)] hover:underline"
              >
                {t("common.signIn")}
              </Link>
            </p>
          </section>
        </div>
      </div>
    </div>
  );
}
