"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { Camera, Loader2, Save, UserRound } from "lucide-react";
import { toast } from "react-toastify";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { apiRequest, apiUrl, mediaUrl } from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";
import { useAuth } from "@/lib/auth-context";
import { useLanguage } from "@/lib/i18n";
import type { User } from "@/lib/types";

type ValidationErrors = Record<string, string[]>;

type ProfileAccount = {
  id?: string | number;
  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;
  status?: string;
  role?: unknown;
  profile_image?: string | null;
};

type ProfilePayload = {
  admin?: ProfileAccount;
  user?: ProfileAccount;
};

type ProfileResponse = {
  statusCode: number;
  success: boolean;
  data: ProfilePayload | ValidationErrors | "" | [];
  message: string;
  message_hi?: string;
};

type ProfileForm = {
  name: string;
  name_hi: string;
  phone: string;
  alternate_phone: string;
  address: string;
  address_hi: string;
};

const emptyProfileForm: ProfileForm = {
  name: "",
  name_hi: "",
  phone: "",
  alternate_phone: "",
  address: "",
  address_hi: "",
};

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

function getErrors(data: ProfileResponse["data"]) {
  if (!data || Array.isArray(data) || typeof data !== "object") {
    return {};
  }

  if ("admin" in data || "user" in data) {
    return {};
  }

  return data as ValidationErrors;
}

function isProfilePayload(
  data: ProfileResponse["data"],
): data is ProfilePayload {
  return (
    !!data &&
    typeof data === "object" &&
    !Array.isArray(data) &&
    ("admin" in data || "user" in data)
  );
}

function firstError(errors: ValidationErrors, field: string) {
  return errors[field]?.[0];
}

function profileFromAccount(account?: ProfileAccount): ProfileForm {
  return {
    name: fieldValue(account?.name),
    name_hi: fieldValue(account?.name_hi),
    phone: fieldValue(account?.phone),
    alternate_phone: fieldValue(account?.alternate_phone),
    address: fieldValue(account?.address),
    address_hi: fieldValue(account?.address_hi),
  };
}

function FieldError({ message }: { message?: string }) {
  if (!message) return null;

  return <p className="mt-2 text-xs font-semibold text-red-600">{message}</p>;
}

function ProfileInput({
  id,
  label,
  value,
  onChange,
  error,
  type = "text",
  disabled,
  helper,
  placeholder,
}: {
  id: string;
  label: string;
  value: string;
  onChange: (value: string) => void;
  error?: string;
  type?: string;
  disabled?: boolean;
  helper?: string;
  placeholder?: string;
}) {
  return (
    <div>
      <Label htmlFor={id} className="text-sm font-black text-slate-950">
        {label}
      </Label>
      <Input
        id={id}
        type={type}
        value={value}
        onChange={(event) => onChange(event.target.value)}
        disabled={disabled}
        placeholder={placeholder}
        className="mt-2 h-11 rounded-xl border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 text-sm font-semibold shadow-none placeholder:text-slate-400 focus-visible:border-[var(--theme-primary)] focus-visible:ring-[var(--theme-primary)]/20 disabled:bg-slate-50 disabled:text-slate-400"
        aria-invalid={!!error}
      />
      {helper && (
        <p className="mt-2 text-xs font-medium text-slate-500">{helper}</p>
      )}
      <FieldError message={error} />
    </div>
  );
}

export function UpdateProfilePage() {
  const { user, token, updateUser } = useAuth();
  const { t } = useLanguage();
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [isPhotoSaving, setIsPhotoSaving] = useState(false);
  const [errors, setErrors] = useState<ValidationErrors>({});
  const [form, setForm] = useState<ProfileForm>(emptyProfileForm);
  const [profileImage, setProfileImage] = useState<string | null>(
    user?.profileImage || null,
  );
  const [profileRole, setProfileRole] = useState<User["role"] | undefined>(
    user?.role,
  );

  const activeToken =
    token ||
    (typeof window !== "undefined" ? localStorage.getItem("auth_token") : null);

  const isAdmin = profileRole === "admin";
  const fullName = form.name || user?.name || "User";
  const initials = useMemo(() => {
    const parts = fullName.trim().split(/\s+/).filter(Boolean);
    return (parts[0]?.[0] || "U") + (parts[1]?.[0] || "");
  }, [fullName]);
  const profileImageUrl = profileImage ? mediaUrl(profileImage) : null;

  const setField = (field: keyof ProfileForm, value: string) => {
    setForm((current) => ({ ...current, [field]: value }));
    setErrors((current) => ({ ...current, [field]: [] }));
  };

  useEffect(() => {
    const loadProfile = async () => {
      setIsLoading(true);
      setErrors({});

      try {
        const response = await apiRequest(apiUrl("/profile"), {
          headers: {
            Authorization: `Bearer ${activeToken || ""}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
        });
        const result = (await response.json()) as ProfileResponse;

        if (!response.ok || !result.success || !isProfilePayload(result.data)) {
          toast.error(
            getLocalizedApiMessage(result, "Unable to fetch profile details."),
          );
          return;
        }

        const account = result.data.admin || result.data.user;
        setProfileRole(result.data.admin ? "admin" : "guide");
        setForm(profileFromAccount(account));
        setProfileImage(account?.profile_image || null);
        if (account?.name) {
          updateUser({
            name: account.name,
            email: account.email || user?.email,
            profileImage: account.profile_image || undefined,
          } as Partial<User>);
        }
      } catch {
        toast.error("Unable to connect to the profile server.");
      } finally {
        setIsLoading(false);
      }
    };

    loadProfile();
  }, [activeToken]);

  const submitProfile = async () => {
    setIsSaving(true);
    setErrors({});

    const name = form.name.trim();
    const profilePayload = {
      name,
      name_hi: form.name_hi,
      phone: form.phone,
      alternate_phone: form.alternate_phone,
      address: form.address,
      address_hi: form.address_hi,
    };

    try {
      const response = await apiRequest(apiUrl("/profile/update"), {
        method: "POST",
        headers: {
          Authorization: `Bearer ${activeToken || ""}`,
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify(profilePayload),
      });
      const result = (await response.json()) as ProfileResponse;

      if (!response.ok || !result.success) {
        setErrors(getErrors(result.data));
        toast.error(getLocalizedApiMessage(result, "Profile update failed."));
        return;
      }

      const account = isProfilePayload(result.data)
        ? result.data.admin || result.data.user
        : undefined;

      updateUser({
        name: account?.name || name,
        email: account?.email || user?.email,
      } as Partial<User>);
      toast.success(
        getLocalizedApiMessage(result, "Profile updated successfully."),
      );
    } catch {
      toast.error("Unable to connect to the profile server.");
    } finally {
      setIsSaving(false);
    }
  };

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

    setIsPhotoSaving(true);
    setErrors({});

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

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

      if (!response.ok || !result.success) {
        setErrors(getErrors(result.data));
        toast.error(
          getLocalizedApiMessage(result, "Profile photo update failed."),
        );
        return;
      }

      const account = isProfilePayload(result.data)
        ? result.data.admin || result.data.user
        : undefined;
      const nextProfileImage = account?.profile_image || null;

      setProfileImage(nextProfileImage);
      updateUser({
        profileImage: nextProfileImage || undefined,
      } as Partial<User>);
      toast.success(
        getLocalizedApiMessage(result, "Profile photo updated successfully."),
      );
    } catch {
      toast.error("Unable to connect to the profile server.");
    } finally {
      setIsPhotoSaving(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };

  const removeProfileImage = async () => {
    setIsPhotoSaving(true);
    setErrors({});

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

      if (!response.ok || !result.success) {
        toast.error(
          getLocalizedApiMessage(result, "Profile photo remove failed."),
        );
        return;
      }

      setProfileImage(null);
      updateUser({ profileImage: undefined } as Partial<User>);
      toast.success(
        getLocalizedApiMessage(result, "Profile photo removed successfully."),
      );
    } catch {
      toast.error("Unable to connect to the profile server.");
    } finally {
      setIsPhotoSaving(false);
    }
  };

  return (
    <div className="w-full">
      <div className="overflow-hidden rounded-2xl bg-white shadow-sm">
        <div className="border-b border-[var(--theme-border)] px-5 py-5 sm:px-6">
          <div className="flex items-center gap-4">
            <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl bg-[var(--theme-primary)] text-white shadow-lg shadow-[var(--theme-primary)]/25">
              <UserRound className="h-6 w-6" />
            </span>
            <div>
              <h1 className="text-2xl font-black text-slate-950">
                {t("admin.manageProfile")}
              </h1>
              <p className="mt-2 text-sm font-medium text-slate-600">
                {t("admin.updatePersonalInformation")}
              </p>
            </div>
          </div>
        </div>

        {isLoading ? (
          <div className="flex min-h-96 items-center justify-center">
            <Loader2 className="h-9 w-9 animate-spin text-[var(--theme-primary)]" />
          </div>
        ) : (
          <>
            <div className="grid items-stretch gap-6 px-5 py-6 sm:px-6 lg:grid-cols-12">
              <aside className="lg:col-span-4">
                <div className="sticky top-20 flex h-full flex-col gap-4 rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-4">
                  <div className="rounded-2xl bg-white p-5 text-center shadow-sm">
                    <div className="relative mx-auto h-24 w-24">
                      <div className="flex h-24 w-24 items-center justify-center rounded-full border border-[var(--theme-border)] bg-[var(--theme-surface)] text-2xl font-black text-[var(--theme-emphasis-text)] shadow-lg">
                        {profileImageUrl ? (
                          <img
                            src={profileImageUrl}
                            alt={t("admin.profilePhoto")}
                            className="h-full w-full rounded-full object-cover"
                          />
                        ) : (
                          initials.toUpperCase()
                        )}
                      </div>
                      <span className="absolute -bottom-1 -right-1 flex h-9 w-9 items-center justify-center rounded-full bg-[var(--theme-primary)] text-white shadow-lg shadow-[var(--theme-primary)]/25">
                        <Camera className="h-4 w-4" />
                      </span>
                    </div>
                    <h2 className="mt-4 text-xl font-black text-slate-950">
                      {fullName}
                    </h2>
                    <p className="mt-1 break-all text-sm font-semibold text-[var(--theme-primary)]">
                      {user?.email || "-"}
                    </p>
                    <p className="mt-1 text-sm font-medium text-slate-600">
                      {form.phone || t("admin.phoneNumber")}
                    </p>
                  </div>

                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/jpeg,image/png,image/gif"
                    className="hidden"
                    onChange={(event) =>
                      uploadProfileImage(event.target.files?.[0])
                    }
                  />
                  <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-1">
                    <Button
                      type="button"
                      onClick={() => fileInputRef.current?.click()}
                      disabled={isPhotoSaving}
                      className="h-11 rounded-xl bg-[var(--theme-primary)] px-6 font-black text-white shadow-lg shadow-[var(--theme-primary)]/20 hover:bg-[var(--theme-accent-dark)]"
                    >
                      {isPhotoSaving
                        ? t("admin.uploading")
                        : t("admin.uploadNew")}
                    </Button>
                    <Button
                      type="button"
                      variant="outline"
                      onClick={removeProfileImage}
                      disabled={isPhotoSaving || !profileImage}
                      className="h-11 rounded-xl border-[var(--theme-border)] bg-white px-5 font-bold"
                    >
                      {t("admin.remove")}
                    </Button>
                  </div>
                </div>
              </aside>

              <section className="lg:col-span-8">
                <div className="h-full rounded-2xl border border-[var(--theme-border)] bg-white p-5 shadow-sm sm:p-6">
                  <h2 className="text-xl font-black text-slate-950">
                    {t("admin.personalInformation")}
                  </h2>
                  <p className="mt-2 text-sm font-medium text-slate-600">
                    {t("admin.updateProfileDetails")}
                  </p>

                  <div className="mt-6 grid gap-6 md:grid-cols-2">
                    <ProfileInput
                      id="profile-name"
                      label={t("admin.fullName")}
                      value={form.name}
                      onChange={(value) => setField("name", value)}
                      error={firstError(errors, "name")}
                      placeholder={t("admin.enterFullName")}
                    />
                    <ProfileInput
                      id="profile-name-hi"
                      label={t("admin.fullNameHindi")}
                      value={form.name_hi}
                      onChange={(value) => setField("name_hi", value)}
                      error={firstError(errors, "name_hi")}
                      placeholder={t("admin.enterFullNameHindi")}
                    />
                    <ProfileInput
                      id="profile-address"
                      label={t("admin.address")}
                      value={form.address}
                      onChange={(value) => setField("address", value)}
                      error={firstError(errors, "address")}
                      placeholder={t("admin.enterAddress")}
                    />
                    <ProfileInput
                      id="profile-address-hi"
                      label={t("admin.addressHindi")}
                      value={form.address_hi}
                      onChange={(value) => setField("address_hi", value)}
                      error={firstError(errors, "address_hi")}
                      placeholder={t("admin.enterAddressHindi")}
                    />
                    <ProfileInput
                      id="profile-phone"
                      label={t("admin.phoneNumber")}
                      value={form.phone}
                      onChange={(value) => setField("phone", value)}
                      error={firstError(errors, "phone")}
                      placeholder={t("admin.enterPhoneNumber")}
                    />
                    <ProfileInput
                      id="profile-alternate-phone"
                      label={t("admin.alternatePhone")}
                      value={form.alternate_phone}
                      onChange={(value) => setField("alternate_phone", value)}
                      error={firstError(errors, "alternate_phone")}
                      placeholder={t("admin.enterAlternatePhone")}
                    />
                  </div>

                  <div className="mt-6 flex justify-end border-t border-[var(--theme-border)] pt-5">
                    <Button
                      type="button"
                      onClick={submitProfile}
                      disabled={isSaving}
                      className="h-11 rounded-xl bg-[var(--theme-primary)] px-6 font-black text-white shadow-lg shadow-[var(--theme-primary)]/25 hover:bg-[var(--theme-accent-dark)]"
                    >
                      {isSaving ? (
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      ) : (
                        <Save className="mr-2 h-4 w-4" />
                      )}
                      {t("admin.saveChanges")}
                    </Button>
                  </div>
                </div>
              </section>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
