"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import {
  Camera,
  CheckCircle2,
  CreditCard,
  Edit,
  Loader2,
  Save,
  X,
} from "lucide-react";
import { toast } from "react-toastify";

import { DashboardBreadcrumb } from "@/components/dashboard/dashboard-breadcrumb";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
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 {
  apiRequest,
  apiUrl,
  mediaUrl,
  shouldBypassImageOptimization,
} from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";
import { useAuth } from "@/lib/auth-context";
import { getGuideById } from "@/lib/mock-data";
import { DISTRICTS, EXPERTISE_AREAS, LANGUAGES } from "@/lib/types";
import { cn } from "@/lib/utils";

type ArrayField = "languages" | "expertise" | "districts";

type GuideProfileForm = {
  name: string;
  nameHi: string;
  email: string;
  phone: string;
  alternatePhone: string;
  address: string;
  addressHi: string;
  bio: string;
  bioHi: string;
  experience: string;
  courseUuid: string;
  courseDistrictUuid: string;
  languages: string[];
  expertise: string[];
  districts: string[];
};

type ProfileOption = {
  uuid?: string;
  district_uuid?: string;
  course_uuid?: string | null;
  title?: string;
  title_hi?: string | null;
  name?: string;
  name_hi?: string | null;
  district_name?: string | null;
  course_location?: string | null;
  course_location_hi?: string | null;
  status?: string;
  district?: ProfileOption | null;
  course?: ProfileOption | null;
  course_district?: ProfileOption | null;
  course_districts?: ProfileOption[] | null;
};

type ProfileUser = {
  uuid?: string;
  name?: string;
  name_hi?: string;
  email?: string;
  phone?: string;
  alternate_phone?: string;
  address?: string;
  address_hi?: string;
  year_of_experience?: string | number;
  bio?: string;
  bio_hi?: string;
  course_uuid?: string | null;
  course?: ProfileOption | null;
  course_district_uuid?: string | null;
  course_district?: ProfileOption | null;
  course_location_uuid?: string | null;
  course_location?: ProfileOption | string | null;
  languages?: ProfileOption[];
  skills?: ProfileOption[];
  locations?: ProfileOption[];
  profile_image?: string | null;
};

type ProfileResponse = {
  success: boolean;
  data?: {
    admin?: ProfileUser;
    user?: ProfileUser;
  };
  message?: string;
  message_hi?: string;
};

type GuideRegistrationOptionsResponse = {
  success: boolean;
  data?: {
    languages?: ProfileOption[];
    skills?: ProfileOption[];
    locations?: ProfileOption[];
    courses?: ProfileOption[];
    course_districts?: ProfileOption[];
    course_locations?: ProfileOption[];
  };
  message?: string;
  message_hi?: string;
};

type GuideRegistrationUpdateResponse = {
  success: boolean;
  message?: string;
  message_hi?: string;
  data?: unknown;
  errors?: unknown;
};

const emptyForm: GuideProfileForm = {
  name: "",
  nameHi: "",
  email: "",
  phone: "",
  alternatePhone: "",
  address: "",
  addressHi: "",
  bio: "",
  bioHi: "",
  experience: "",
  courseUuid: "",
  courseDistrictUuid: "",
  languages: [],
  expertise: [],
  districts: [],
};

function valueToString(value: unknown) {
  return value === null || value === undefined ? "" : String(value);
}

function fallbackOptions(titles: string[]): ProfileOption[] {
  return titles.map((title) => ({ uuid: title, title, status: "active" }));
}

function activeOptions(
  options: ProfileOption[] | undefined,
  fallback: string[] = [],
) {
  const active = (options || []).filter(
    (option) => option.status !== "inactive",
  );
  return active.length ? active : fallbackOptions(fallback);
}

function optionValue(option: ProfileOption) {
  return option.uuid || option.district_uuid || option.title || option.name || "";
}

function optionLabel(option: ProfileOption) {
  return (
    option.title ||
    option.name ||
    option.district_name ||
    option.course_location ||
    option.district?.title ||
    option.district?.name ||
    option.district?.district_name ||
    option.uuid ||
    ""
  );
}

function selectedValues(options?: ProfileOption[]) {
  return (options || [])
    .map((option) => option.uuid || option.title || option.name)
    .filter((value): value is string => Boolean(value));
}

function selectedToUuids(selected: string[], options: ProfileOption[]) {
  return selected
    .map((value) => {
      const option = options.find(
        (item) => optionValue(item) === value || optionLabel(item) === value,
      );
      return option ? optionValue(option) : value;
    })
    .filter(Boolean);
}

function selectedLabels(selected: string[], options: ProfileOption[]) {
  return selected.map((value) => {
    const option = options.find(
      (item) => optionValue(item) === value || optionLabel(item) === value,
    );
    return option ? optionLabel(option) : value;
  });
}

function findOption(value: string, options: ProfileOption[]) {
  if (!value) return undefined;
  return options.find(
    (item) => optionValue(item) === value || optionLabel(item) === value,
  );
}

function selectedLabel(value: string, options: ProfileOption[]) {
  const option = findOption(value, options);
  return option ? optionLabel(option) : value;
}

function uniqueOptions(options: ProfileOption[]) {
  return options.filter(
    (option, index, list) =>
      list.findIndex((item) => optionValue(item) === optionValue(option)) ===
      index,
  );
}

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

function 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 (typeof value === "object") {
    return Object.entries(value as Record<string, unknown>).flatMap(
      ([key, item]) =>
        collectValidationMessages(
          item,
          parentKey ? `${parentKey}.${key}` : key,
        ),
    );
  }

  return [];
}

function getProfileValidationMessages(result: GuideRegistrationUpdateResponse) {
  const messages = [
    ...collectValidationMessages(result.errors),
    ...collectValidationMessages(result.data),
  ];

  return Array.from(new Set(messages));
}

function DetailItem({ label, value }: { label: string; value?: string }) {
  return (
    <div className="rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-4">
      <p className="text-xs font-bold uppercase tracking-wide text-muted-foreground">
        {label}
      </p>
      <p className="mt-2 min-h-5 text-sm font-bold text-foreground">
        {value || "-"}
      </p>
    </div>
  );
}

export default function ProfilePage() {
  const { user, token, updateUser } = useAuth();
  const guide = user?.guideId ? getGuideById(user.guideId) : undefined;
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [isLoadingProfile, setIsLoadingProfile] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [isPhotoSaving, setIsPhotoSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [validationErrors, setValidationErrors] = useState<string[]>([]);
  const [guideUuid, setGuideUuid] = useState("");
  const [profileImage, setProfileImage] = useState<string | null>(null);
  const [formData, setFormData] = useState<GuideProfileForm>({
    ...emptyForm,
    name: guide?.name || user?.name || "",
    email: guide?.email || user?.email || "",
    phone: guide?.phone || "",
    address: guide?.address || "",
    bio: guide?.bio || "",
    experience: guide?.experience?.toString() || "",
    languages: guide?.languages || [],
    expertise: guide?.expertise || [],
    districts: guide?.districts || [],
  });
  const [profileOptions, setProfileOptions] = useState({
    languages: fallbackOptions(LANGUAGES),
    skills: fallbackOptions(EXPERTISE_AREAS),
    locations: fallbackOptions(DISTRICTS),
    courses: [] as ProfileOption[],
    courseDistricts: [] as ProfileOption[],
  });

  const photo = profileImage
    ? mediaUrl(profileImage)
    : guide?.photo || "/placeholder.png";

  useEffect(() => {
    const activeToken = token || localStorage.getItem("auth_token");

    if (!activeToken) {
      setIsLoadingProfile(false);
      return;
    }

    const loadProfile = async () => {
      setIsLoadingProfile(true);

      try {
        const [profileResponse, optionsResponse] = await Promise.all([
          apiRequest(apiUrl("/profile"), {
            headers: {
              Authorization: `Bearer ${activeToken}`,
              Accept: "application/json",
              "Content-Type": "application/json",
            },
          }),
          apiRequest(apiUrl("/guide-registration/options"), {
            headers: {
              Authorization: `Bearer ${activeToken}`,
              Accept: "application/json",
              "Content-Type": "application/json",
            },
          }),
        ]);

        const profileResult = (await profileResponse.json()) as ProfileResponse;
        const optionsResult =
          (await optionsResponse.json()) as GuideRegistrationOptionsResponse;

        if (
          !profileResponse.ok ||
          !profileResult.success ||
          !profileResult.data?.user
        ) {
          throw new Error(
            getLocalizedApiMessage(profileResult, "Unable to fetch profile."),
          );
        }

        if (optionsResponse.ok && optionsResult.success) {
          setProfileOptions({
            languages: activeOptions(optionsResult.data?.languages, LANGUAGES),
            skills: activeOptions(optionsResult.data?.skills, EXPERTISE_AREAS),
            locations: activeOptions(optionsResult.data?.locations, DISTRICTS),
            courses: activeOptions(optionsResult.data?.courses),
            courseDistricts: activeOptions(
              optionsResult.data?.course_districts ||
                optionsResult.data?.course_locations,
            ),
          });
        }

        const profile = profileResult.data.user;
        setGuideUuid(profile.uuid || "");
        setProfileImage(profile.profile_image || null);
        const nextForm: GuideProfileForm = {
          name: valueToString(profile.name) || guide?.name || user?.name || "",
          nameHi: valueToString(profile.name_hi),
          email:
            valueToString(profile.email) || guide?.email || user?.email || "",
          phone: valueToString(profile.phone) || guide?.phone || "",
          alternatePhone: valueToString(profile.alternate_phone),
          address: valueToString(profile.address) || guide?.address || "",
          addressHi: valueToString(profile.address_hi),
          bio: valueToString(profile.bio) || guide?.bio || "",
          bioHi: valueToString(profile.bio_hi),
          experience:
            valueToString(profile.year_of_experience) ||
            guide?.experience?.toString() ||
            "",
          courseUuid: valueToString(
            profile.course_uuid ||
              profile.course?.course?.uuid ||
              profile.course?.course_uuid ||
              profile.course_district?.course_uuid ||
              profile.course_district?.course?.uuid ||
              profile.course?.uuid,
          ),
          courseDistrictUuid: valueToString(
            profile.course_district_uuid ||
              profile.course_district?.uuid ||
              profile.course?.course_district?.uuid ||
              profile.course_location_uuid ||
              (typeof profile.course_location === "object" &&
              profile.course_location
                ? profile.course_location.uuid
                : "") ||
              (profile.course?.course_uuid ||
              profile.course?.district_uuid ||
              profile.course?.district
                ? profile.course?.uuid
                : ""),
          ),
          languages: selectedValues(profile.languages).length
            ? selectedValues(profile.languages)
            : guide?.languages || [],
          expertise: selectedValues(profile.skills).length
            ? selectedValues(profile.skills)
            : guide?.expertise || [],
          districts: selectedValues(profile.locations).length
            ? selectedValues(profile.locations)
            : guide?.districts || [],
        };

        setFormData(nextForm);

        if (profile.name) {
          updateUser({
            name: profile.name,
            email: profile.email || user?.email,
            profileImage: profile.profile_image || undefined,
          });
        }
      } catch (error) {
        toast.error(
          error instanceof Error ? error.message : "Unable to fetch profile.",
        );
      } finally {
        setIsLoadingProfile(false);
      }
    };

    loadProfile();
  }, [token, updateUser, user?.email]);

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

    const activeToken = token || localStorage.getItem("auth_token");

    if (!activeToken) {
      toast.error("Please log in again to update your profile photo.");
      return;
    }

    setIsPhotoSaving(true);
    setValidationErrors([]);

    const uploadPayload = new FormData();
    uploadPayload.append("profile_image", file);

    try {
      const response = await apiRequest(
        apiUrl("/profile/change-profile-image"),
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${activeToken}`,
            Accept: "application/json",
          },
          body: uploadPayload,
        },
      );
      const result = (await response.json()) as ProfileResponse;

      if (!response.ok || !result.success) {
        throw new Error(
          getLocalizedApiMessage(result, "Profile photo update failed."),
        );
      }

      const profile = result.data?.user || result.data?.admin;
      const nextProfileImage = profile?.profile_image || null;

      setProfileImage(nextProfileImage);
      updateUser({ profileImage: nextProfileImage || undefined });
      toast.success(
        getLocalizedApiMessage(result, "Profile photo updated successfully."),
      );
    } catch (photoError) {
      toast.error(
        photoError instanceof Error
          ? photoError.message
          : "Profile photo update failed.",
      );
    } finally {
      setIsPhotoSaving(false);

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

  const toggleArrayItem = (
    field: ArrayField,
    value: string,
    label?: string,
  ) => {
    setFormData((prev) => ({
      ...prev,
      [field]:
        prev[field].includes(value) ||
        (label ? prev[field].includes(label) : false)
          ? prev[field].filter((item) => item !== value && item !== label)
          : [...prev[field], value],
    }));
  };

  const handleSave = async () => {
    const activeToken = token || localStorage.getItem("auth_token");
    const activeGuideUuid = guideUuid || user?.guideId || user?.id;

    if (!activeGuideUuid) {
      toast.error("Guide UUID not found. Please refresh and try again.");
      return;
    }

    setIsSaving(true);
    setValidationErrors([]);

    try {
      const payload = {
        name: formData.name,
        email: formData.email,
        phone: formData.phone,
        address: formData.address,
        year_of_experience: formData.experience
          ? Number(formData.experience)
          : "",
        bio: formData.bio,
        course_uuid: formData.courseUuid,
        course_district_uuid: formData.courseDistrictUuid,
        language_uuids: selectedToUuids(
          formData.languages,
          profileOptions.languages,
        ),
        skill_uuids: selectedToUuids(formData.expertise, profileOptions.skills),
        location_uuids: selectedToUuids(
          formData.districts,
          profileOptions.locations,
        ),
      };

      const response = await apiRequest(
        apiUrl(`/guide-registration/${activeGuideUuid}`),
        {
          method: "PUT",
          headers: {
            Authorization: `Bearer ${activeToken || ""}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        },
      );
      const result = (await response.json()) as GuideRegistrationUpdateResponse;

      if (!response.ok || !result.success) {
        const messages = getProfileValidationMessages(result);
        setValidationErrors(
          messages.length
            ? messages
            : [getLocalizedApiMessage(result, "Profile update failed.")],
        );
        toast.error(getLocalizedApiMessage(result, "Profile update failed."));
        return;
      }

      updateUser({ name: formData.name, email: formData.email });
      toast.success(
        getLocalizedApiMessage(result, "Profile updated successfully."),
      );
      setSaved(true);
      setValidationErrors([]);
      setIsEditing(false);
      setTimeout(() => setSaved(false), 3000);
    } catch {
      toast.error("Unable to connect to the profile update server.");
    } finally {
      setIsSaving(false);
    }
  };

  const renderSelection = (field: ArrayField, options: ProfileOption[]) => (
    <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
      {options.map((option) => {
        const value = optionValue(option);
        const label = optionLabel(option);
        const selected =
          formData[field].includes(value) || formData[field].includes(label);

        return (
          <button
            key={value}
            type="button"
            onClick={() => toggleArrayItem(field, value, label)}
            className={cn(
              "rounded-2xl border p-4 text-left text-sm font-bold transition",
              selected
                ? "border-[var(--theme-secondary)] bg-[var(--theme-surface-strong)] text-[var(--theme-emphasis-text)] shadow-sm"
                : "border-[var(--theme-border)] bg-white text-foreground hover:border-[var(--theme-secondary)]/60",
            )}
          >
            <span className="flex items-center gap-3">
              <span
                className={cn(
                  "flex h-5 w-5 items-center justify-center rounded-full border",
                  selected
                    ? "border-[var(--theme-primary)] bg-[var(--theme-primary)] text-white"
                    : "border-[var(--theme-border)] bg-[var(--theme-surface)]",
                )}
              >
                {selected && <CheckCircle2 className="h-3.5 w-3.5" />}
              </span>
              {label}
            </span>
          </button>
        );
      })}
    </div>
  );

  const languages = selectedLabels(
    formData.languages,
    profileOptions.languages,
  );
  const expertise = selectedLabels(formData.expertise, profileOptions.skills);
  const districts = selectedLabels(
    formData.districts,
    profileOptions.locations,
  );
  const selectedCourse = findOption(formData.courseUuid, profileOptions.courses);
  const selectedCourseUuid = selectedCourse?.uuid || formData.courseUuid;
  const courseDistrictOptions = selectedCourseUuid
    ? uniqueOptions([
        ...(selectedCourse?.course_districts || []),
        ...profileOptions.courseDistricts.filter(
          (option) =>
            (option.course_uuid || option.course?.uuid) === selectedCourseUuid,
        ),
      ])
    : [];
  const courseLabel = selectedLabel(formData.courseUuid, profileOptions.courses);
  const courseDistrictLabel = selectedLabel(
    formData.courseDistrictUuid,
    courseDistrictOptions.length
      ? courseDistrictOptions
      : profileOptions.courseDistricts,
  );

  return (
    <div className="w-full space-y-5">
      <DashboardBreadcrumb current="Profile Settings" />

      <div className="flex flex-col gap-4 rounded-3xl border border-[var(--theme-border)] bg-white p-5 shadow-sm sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-black text-foreground">
            Profile Settings
          </h1>
          <p className="mt-1 text-sm font-medium text-muted-foreground">
            View and manage your guide profile information
          </p>
        </div>
        {!isEditing && (
          <div className="flex flex-wrap gap-3 sm:justify-end">
            <Button
              asChild
              variant="outline"
              className="rounded-full border-[var(--theme-border)] bg-white px-6 font-black text-[var(--theme-primary)] shadow-sm hover:bg-[var(--theme-surface)] hover:text-[var(--theme-primary)]"
            >
              <Link href="/dashboard/id-card">
                <CreditCard className="mr-2 h-4 w-4" />
                Get My ID Card
              </Link>
            </Button>
            <Button
              type="button"
              onClick={() => setIsEditing(true)}
              className="rounded-full bg-gradient-to-r from-[var(--theme-secondary)] to-[var(--theme-accent)] px-6 font-black text-white shadow-lg shadow-[var(--theme-secondary)]/25 hover:from-[var(--theme-primary)] hover:to-[var(--theme-primary-dark)]"
            >
              <Edit className="mr-2 h-4 w-4" />
              Update Profile
            </Button>
          </div>
        )}
      </div>

      {saved && (
        <Alert className="rounded-2xl border-emerald-200 bg-emerald-50">
          <CheckCircle2 className="h-4 w-4 text-emerald-600" />
          <AlertDescription>Profile updated successfully!</AlertDescription>
        </Alert>
      )}

      {isLoadingProfile ? (
        <div className="flex min-h-80 items-center justify-center rounded-3xl border border-[var(--theme-border)] bg-white">
          <Loader2 className="h-9 w-9 animate-spin text-[var(--theme-primary)]" />
        </div>
      ) : isEditing ? (
        <div className="rounded-3xl border border-[var(--theme-border)] bg-white p-4 shadow-sm sm:p-6">
          <div className="mb-6 flex items-center gap-6 rounded-2xl bg-[var(--theme-surface-soft)] p-4">
            <div className="relative h-24 w-24 overflow-hidden rounded-full">
              <Image
                src={photo}
                alt={formData.name || "Guide"}
                fill
                className="object-cover"
                unoptimized={shouldBypassImageOptimization(photo)}
              />
            </div>
            <div>
              <p className="text-sm font-medium text-muted-foreground">
                Upload a professional photo. Square images work best.
              </p>
              <input
                ref={fileInputRef}
                type="file"
                accept="image/jpeg,image/png,image/gif,image/webp"
                className="hidden"
                onChange={(event) => handlePhotoChange(event.target.files?.[0])}
              />
              <Button
                type="button"
                variant="outline"
                size="sm"
                disabled={isPhotoSaving}
                onClick={() => fileInputRef.current?.click()}
                className="mt-3 rounded-full"
              >
                <Camera className="mr-2 h-4 w-4" />
                {isPhotoSaving ? "Uploading..." : "Change Photo"}
              </Button>
            </div>
          </div>

          {validationErrors.length > 0 && (
            <Alert className="mb-6 rounded-2xl border-red-200 bg-red-50 text-red-700">
              <AlertDescription className="text-sm font-semibold text-red-700">
                <p className="mb-2 font-black">Please fix the following:</p>
                <ul className="list-disc space-y-1 pl-5">
                  {validationErrors.map((message, index) => (
                    <li key={`${message}-${index}`}>{message}</li>
                  ))}
                </ul>
              </AlertDescription>
            </Alert>
          )}

          <div className="grid gap-6 xl:grid-cols-12">
            <div className="space-y-8 xl:col-span-8">
              <section className="rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-4">
                <div className="mb-4">
                  <h2 className="text-xl font-black text-foreground">
                    Personal Details
                  </h2>
                  <p className="mt-1 text-sm text-muted-foreground">
                    Basic name, contact, and address information.
                  </p>
                </div>
                <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
                  <div className="space-y-2">
                    <Label htmlFor="name">Full Name *</Label>
                    <Input
                      id="name"
                      value={formData.name}
                      onChange={(event) =>
                        setFormData({ ...formData, name: event.target.value })
                      }
                      className="h-11 rounded-xl border-[var(--theme-border)] bg-white"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="nameHi">Full Name in Hindi</Label>
                    <Input
                      id="nameHi"
                      value={formData.nameHi}
                      onChange={(event) =>
                        setFormData({ ...formData, nameHi: event.target.value })
                      }
                      className="h-11 rounded-xl border-[var(--theme-border)] bg-white"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="email">Email *</Label>
                    <Input
                      id="email"
                      type="email"
                      value={formData.email}
                      readOnly
                      aria-readonly="true"
                      className="h-11 cursor-not-allowed rounded-xl border-[var(--theme-border)] bg-slate-50 text-muted-foreground"
                    />
                    <p className="text-xs font-medium text-muted-foreground">
                      Email cannot be changed.
                    </p>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="phone">Phone Number *</Label>
                    <Input
                      id="phone"
                      value={formData.phone}
                      onChange={(event) =>
                        setFormData({ ...formData, phone: event.target.value })
                      }
                      className="h-11 rounded-xl border-[var(--theme-border)] bg-white"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="alternatePhone">
                      Alternate Phone Number
                    </Label>
                    <Input
                      id="alternatePhone"
                      value={formData.alternatePhone}
                      onChange={(event) =>
                        setFormData({
                          ...formData,
                          alternatePhone: event.target.value,
                        })
                      }
                      className="h-11 rounded-xl border-[var(--theme-border)] bg-white"
                    />
                  </div>
                  <div className="space-y-2 xl:col-span-2">
                    <Label htmlFor="address">Address *</Label>
                    <Input
                      id="address"
                      value={formData.address}
                      onChange={(event) =>
                        setFormData({
                          ...formData,
                          address: event.target.value,
                        })
                      }
                      className="h-11 rounded-xl border-[var(--theme-border)] bg-white"
                    />
                  </div>
                  <div className="space-y-2 xl:col-span-2">
                    <Label htmlFor="addressHi">Address in Hindi</Label>
                    <Input
                      id="addressHi"
                      value={formData.addressHi}
                      onChange={(event) =>
                        setFormData({
                          ...formData,
                          addressHi: event.target.value,
                        })
                      }
                      className="h-11 rounded-xl border-[var(--theme-border)] bg-white"
                    />
                  </div>
                </div>
              </section>

              <section className="rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-4">
                <div className="mb-4">
                  <h2 className="text-xl font-black text-foreground">
                    Professional Details
                  </h2>
                  <p className="mt-1 text-sm text-muted-foreground">
                    Experience and guide biography.
                  </p>
                </div>
                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="courseUuid">Guide Course</Label>
                    <select
                      id="courseUuid"
                      value={formData.courseUuid}
                      onChange={(event) =>
                        setFormData({
                          ...formData,
                          courseUuid: event.target.value,
                          courseDistrictUuid: "",
                        })
                      }
                      disabled={profileOptions.courses.length === 0}
                      className="h-11 w-full rounded-xl border border-[var(--theme-border)] bg-white px-3 text-sm font-semibold text-foreground disabled:cursor-not-allowed disabled:bg-slate-50 disabled:text-muted-foreground"
                    >
                      <option value="">
                        {profileOptions.courses.length
                          ? "Select course"
                          : "No courses available"}
                      </option>
                      {profileOptions.courses.map((option) => {
                        const value = optionValue(option);
                        return (
                          <option key={value} value={value}>
                            {optionLabel(option)}
                          </option>
                        );
                      })}
                    </select>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="courseDistrictUuid">Course District</Label>
                    <select
                      id="courseDistrictUuid"
                      value={formData.courseDistrictUuid}
                      onChange={(event) =>
                        setFormData({
                          ...formData,
                          courseDistrictUuid: event.target.value,
                        })
                      }
                      disabled={
                        !formData.courseUuid ||
                        courseDistrictOptions.length === 0
                      }
                      className="h-11 w-full rounded-xl border border-[var(--theme-border)] bg-white px-3 text-sm font-semibold text-foreground disabled:cursor-not-allowed disabled:bg-slate-50 disabled:text-muted-foreground"
                    >
                      <option value="">
                        {!formData.courseUuid
                          ? "Select course first"
                          : courseDistrictOptions.length
                            ? "Select course district"
                            : "No course districts available"}
                      </option>
                      {courseDistrictOptions.map((option) => {
                        const value = optionValue(option);
                        return (
                          <option key={value} value={value}>
                            {optionLabel(option)}
                          </option>
                        );
                      })}
                    </select>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="experience">Experience (years) *</Label>
                    <Input
                      id="experience"
                      type="number"
                      value={formData.experience}
                      onChange={(event) =>
                        setFormData({
                          ...formData,
                          experience: event.target.value,
                        })
                      }
                      className="h-11 rounded-xl border-[var(--theme-border)] bg-white"
                    />
                  </div>
                  <div className="space-y-2 sm:col-span-2">
                    <Label htmlFor="bio">Bio *</Label>
                    <Textarea
                      id="bio"
                      value={formData.bio}
                      onChange={(event) =>
                        setFormData({ ...formData, bio: event.target.value })
                      }
                      rows={4}
                      className="rounded-xl border-[var(--theme-border)] bg-white"
                    />
                  </div>
                  <div className="space-y-2 sm:col-span-2">
                    <Label htmlFor="bioHi">Bio in Hindi</Label>
                    <Textarea
                      id="bioHi"
                      value={formData.bioHi}
                      onChange={(event) =>
                        setFormData({ ...formData, bioHi: event.target.value })
                      }
                      rows={4}
                      className="rounded-xl border-[var(--theme-border)] bg-white"
                    />
                  </div>
                </div>
              </section>

              <section className="rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-4">
                <div className="mb-4">
                  <h2 className="text-xl font-black text-foreground">
                    Spoken Languages & Expertise
                  </h2>
                  <p className="mt-1 text-sm text-muted-foreground">
                    Select spoken languages and guide skill areas.
                  </p>
                </div>
                <div className="space-y-5">
                  <div className="space-y-3">
                    <Label>Spoken Languages *</Label>
                    {renderSelection("languages", profileOptions.languages)}
                  </div>
                  <div className="space-y-3">
                    <Label>Expertise *</Label>
                    {renderSelection("expertise", profileOptions.skills)}
                  </div>
                </div>
              </section>

              <section className="rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-4">
                <div className="mb-4">
                  <h2 className="text-xl font-black text-foreground">
                    Areas of Operation
                  </h2>
                  <p className="mt-1 text-sm text-muted-foreground">
                    Select service locations where you provide guide services.
                  </p>
                </div>
                <div className="space-y-3">
                  <Label>Service Locations *</Label>
                  {renderSelection("districts", profileOptions.locations)}
                </div>
              </section>
            </div>

            <aside className="xl:col-span-4">
              <div className="sticky top-20 space-y-4 rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-4">
                <div className="rounded-2xl bg-white p-4 text-center shadow-sm">
                  <div className="relative mx-auto h-24 w-24 overflow-hidden rounded-full ring-4 ring-[var(--theme-surface-strong)]">
                    <Image
                      src={photo}
                      alt={formData.name || "Guide"}
                      fill
                      className="object-cover"
                      unoptimized={shouldBypassImageOptimization(photo)}
                    />
                  </div>
                  <h3 className="mt-4 text-xl font-black text-foreground">
                    {formData.name || "Guide Profile"}
                  </h3>
                  <p className="mt-1 break-all text-sm font-semibold text-[var(--theme-primary)]">
                    {formData.email || "-"}
                  </p>
                  <p className="mt-1 text-sm text-muted-foreground">
                    {formData.phone || "Contact not available"}
                  </p>
                </div>

                <div className="grid gap-3">
                  <DetailItem
                    label="Experience"
                    value={
                      formData.experience ? `${formData.experience} years` : ""
                    }
                  />
                  <DetailItem label="Guide Course" value={courseLabel} />
                  <DetailItem
                    label="Course District"
                    value={courseDistrictLabel}
                  />
                  <DetailItem label="Address" value={formData.address} />
                </div>

                <div className="rounded-2xl border border-[var(--theme-border)] bg-white p-4">
                  <p className="mb-3 text-xs font-bold uppercase tracking-wide text-muted-foreground">
                    Spoken Languages
                  </p>
                  <div className="flex flex-wrap gap-2">
                    {languages.length ? (
                      languages.map((language, index) => (
                        <Badge
                          key={`${language}-${index}`}
                          className="rounded-full bg-[var(--theme-surface-strong)] text-[var(--theme-emphasis-text)] hover:bg-[var(--theme-surface-strong)]"
                        >
                          {language}
                        </Badge>
                      ))
                    ) : (
                      <p className="text-sm text-muted-foreground">-</p>
                    )}
                  </div>
                </div>

                <div className="rounded-2xl border border-[var(--theme-border)] bg-white p-4">
                  <p className="mb-3 text-xs font-bold uppercase tracking-wide text-muted-foreground">
                    Expertise
                  </p>
                  <div className="flex flex-wrap gap-2">
                    {expertise.length ? (
                      expertise.map((item, index) => (
                        <Badge
                          key={`${item}-${index}`}
                          className="rounded-full bg-[var(--theme-surface-strong)] text-[var(--theme-emphasis-text)] hover:bg-[var(--theme-surface-strong)]"
                        >
                          {item}
                        </Badge>
                      ))
                    ) : (
                      <p className="text-sm text-muted-foreground">-</p>
                    )}
                  </div>
                </div>

                <div className="rounded-2xl border border-[var(--theme-border)] bg-white p-4">
                  <p className="mb-3 text-xs font-bold uppercase tracking-wide text-muted-foreground">
                    Areas of Operation
                  </p>
                  <div className="flex flex-wrap gap-2">
                    {districts.length ? (
                      districts.map((district, index) => (
                        <Badge
                          key={`${district}-${index}`}
                          className="rounded-full bg-[var(--theme-surface-strong)] text-[var(--theme-emphasis-text)] hover:bg-[var(--theme-surface-strong)]"
                        >
                          {district}
                        </Badge>
                      ))
                    ) : (
                      <p className="text-sm text-muted-foreground">-</p>
                    )}
                  </div>
                </div>
              </div>
            </aside>
          </div>

          <div className="mt-6 flex justify-end gap-3">
            <Button
              type="button"
              variant="outline"
              onClick={() => setIsEditing(false)}
              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)]"
            >
              <X className="mr-2 h-4 w-4" />
              Cancel
            </Button>
            <Button
              type="button"
              onClick={handleSave}
              disabled={isSaving}
              className="rounded-full bg-gradient-to-r from-[var(--theme-secondary)] to-[var(--theme-accent)] px-7 font-black text-white shadow-lg shadow-[var(--theme-secondary)]/25 hover:from-[var(--theme-primary)] hover:to-[var(--theme-primary-dark)]"
            >
              {isSaving ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : (
                <Save className="mr-2 h-4 w-4" />
              )}
              Submit
            </Button>
          </div>
        </div>
      ) : (
        <div className="rounded-3xl border border-[var(--theme-border)] bg-white p-4 shadow-sm sm:p-6">
          <div className="mb-6 flex items-center gap-6 rounded-2xl bg-[var(--theme-surface-soft)] p-4">
            <div className="relative h-24 w-24 overflow-hidden rounded-full">
              <Image
                src={photo}
                alt={formData.name || "Guide"}
                fill
                className="object-cover"
                unoptimized={shouldBypassImageOptimization(photo)}
              />
            </div>
            <div>
              <h2 className="text-2xl font-black text-foreground">
                {formData.name || "Guide Profile"}
              </h2>
              <p className="mt-1 text-sm font-medium text-muted-foreground">
                {formData.email || "Email not available"}
              </p>
            </div>
          </div>

          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
            <DetailItem label="Full Name" value={formData.name} />
            <DetailItem label="Full Name in Hindi" value={formData.nameHi} />
            <DetailItem label="Email" value={formData.email} />
            <DetailItem label="Phone Number" value={formData.phone} />
            <DetailItem
              label="Alternate Phone"
              value={formData.alternatePhone}
            />
            <DetailItem
              label="Experience"
              value={formData.experience ? `${formData.experience} years` : ""}
            />
            <DetailItem label="Guide Course" value={courseLabel} />
            <DetailItem label="Course District" value={courseDistrictLabel} />
            <DetailItem label="Address" value={formData.address} />
            <DetailItem label="Address in Hindi" value={formData.addressHi} />
          </div>

          <div className="mt-4 grid gap-4 lg:grid-cols-2">
            <DetailItem label="Bio" value={formData.bio} />
            <DetailItem label="Bio in Hindi" value={formData.bioHi} />
          </div>

          <div className="mt-6 grid gap-4 lg:grid-cols-3">
            <div className="rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-4">
              <p className="mb-3 text-xs font-bold uppercase tracking-wide text-muted-foreground">
                Spoken Languages
              </p>
              <div className="flex flex-wrap gap-2">
                {languages.length ? (
                  languages.map((language, index) => (
                    <Badge
                      key={`${language}-${index}`}
                      className="rounded-full bg-[var(--theme-surface-strong)] text-[var(--theme-emphasis-text)] hover:bg-[var(--theme-surface-strong)]"
                    >
                      {language}
                    </Badge>
                  ))
                ) : (
                  <p className="text-sm text-muted-foreground">-</p>
                )}
              </div>
            </div>
            <div className="rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-4">
              <p className="mb-3 text-xs font-bold uppercase tracking-wide text-muted-foreground">
                Expertise
              </p>
              <div className="flex flex-wrap gap-2">
                {expertise.length ? (
                  expertise.map((item, index) => (
                    <Badge
                      key={`${item}-${index}`}
                      className="rounded-full bg-[var(--theme-surface-strong)] text-[var(--theme-emphasis-text)] hover:bg-[var(--theme-surface-strong)]"
                    >
                      {item}
                    </Badge>
                  ))
                ) : (
                  <p className="text-sm text-muted-foreground">-</p>
                )}
              </div>
            </div>
            <div className="rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-4">
              <p className="mb-3 text-xs font-bold uppercase tracking-wide text-muted-foreground">
                Areas of Operation
              </p>
              <div className="flex flex-wrap gap-2">
                {districts.length ? (
                  districts.map((district, index) => (
                    <Badge
                      key={`${district}-${index}`}
                      className="rounded-full bg-[var(--theme-surface-strong)] text-[var(--theme-emphasis-text)] hover:bg-[var(--theme-surface-strong)]"
                    >
                      {district}
                    </Badge>
                  ))
                ) : (
                  <p className="text-sm text-muted-foreground">-</p>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
