"use client";

import { useEffect, useRef, useState, type FormEvent, type ChangeEvent } from "react";
import Image from "next/image";
import { BadgeCheck, Camera, Clock, ShieldAlert, XCircle } from "lucide-react";

import { Container } from "@/components/common/Container";
import { Card, CardContent } from "@/components/common/Card";
import { Button } from "@/components/common/Button";
import { FormField } from "@/components/app/FormField";
import { CountrySelect } from "@/components/app/CountrySelect";
import { useProfileInfo, useUpdateProfile } from "@/hooks/queries/useProfile";
import { isApiError } from "@/lib/apiError";
import { useTranslation } from "@/hooks/useTranslation";
import { cn } from "@/lib/utils";

const KYC_BADGE = {
  0: { icon: ShieldAlert, key: "app.profile.kycUnverified", cls: "bg-amber-50 text-amber-700 dark:bg-amber-500/15 dark:text-amber-300" },
  1: { icon: BadgeCheck, key: "app.profile.kycVerified",   cls: "bg-accent-50 text-accent-700 dark:bg-accent-500/15 dark:text-accent-300" },
  2: { icon: Clock,      key: "app.profile.kycPending",    cls: "bg-amber-50 text-amber-700 dark:bg-amber-500/15 dark:text-amber-300" },
  3: { icon: XCircle,    key: "app.profile.kycRejected",   cls: "bg-rose-50 text-rose-700 dark:bg-rose-500/15 dark:text-rose-300" },
} as const;

// Page labels — 14px, medium weight.
const FIELD_LABEL_CLASSNAME =
  "block text-[length:var(--text-sm-fixed)] font-medium capitalize text-slate-500 dark:text-slate-400";

export default function ProfilePage() {
  const { t } = useTranslation();
  const { data, isLoading } = useProfileInfo();
  const { mutateAsync, isPending } = useUpdateProfile();

  const info = data?.user_info;
  const paths = data?.image_paths;
  const countries = data?.countries ?? [];

  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName]   = useState("");
  const [phone, setPhone]         = useState("");
  const [dob, setDob]             = useState("");
  const [country, setCountry]     = useState("");
  const [address, setAddress]     = useState("");
  const [city, setCity]           = useState("");
  const [stateVal, setStateVal]   = useState("");
  const [zip, setZip]             = useState("");
  const [formError, setFormError] = useState("");
  const [savedAt, setSavedAt]     = useState<number | null>(null);
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Revoke the object URL when it's replaced or on unmount to avoid memory leaks.
  useEffect(() => {
    return () => {
      if (previewUrl) URL.revokeObjectURL(previewUrl);
    };
  }, [previewUrl]);

  useEffect(() => {
    if (!info) return;
    setFirstName(info.firstname || info.first_name || "");
    setLastName(info.lastname || info.last_name || "");
    setPhone(info.full_mobile || info.mobile || "");
    setDob(info.date_of_birth ?? "");
    setCountry(info.country ?? "");
    setAddress(info.address ?? "");
    setCity(info.city ?? "");
    setStateVal(info.state ?? "");
    setZip(info.zip ?? "");
  }, [info]);

  useEffect(() => {
    if (!savedAt) return;
    const id = window.setTimeout(() => setSavedAt(null), 2000);
    return () => window.clearTimeout(id);
  }, [savedAt]);

  function handleImageChange(e: ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    e.target.value = ""; // allow re-selecting the same file
    if (previewUrl) URL.revokeObjectURL(previewUrl);
    setImageFile(file);
    setPreviewUrl(URL.createObjectURL(file));
  }

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setFormError("");
    try {
      await mutateAsync({
        firstname: firstName,
        lastname: lastName,
        phone,
        date_of_birth: dob || undefined,
        country,
        address,
        city,
        state: stateVal,
        zip_code: zip,
        image: imageFile ?? undefined,
      });
      setImageFile(null);
      setPreviewUrl(null);
      setSavedAt(Date.now());
    } catch (err) {
      setFormError(isApiError(err) ? err.message : t("app.auth.errors.generic"));
    }
  }

  const email    = info?.email ?? "";
  const initials = `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase() || email.charAt(0).toUpperCase();
  const kycNum   = (info?.kyc_verified ?? 0) as 0 | 1 | 2 | 3;
  const badge    = KYC_BADGE[kycNum] ?? KYC_BADGE[0];
  const BadgeIcon = badge.icon;

  const serverAvatarUrl = paths
    ? info?.image
      ? `${paths.base_url}${paths.path_location}/${info.image}`
      : `${paths.base_url}${paths.default_image}`
    : null;
  // Local preview takes priority; falls back to server URL (or default image)
  const avatarUrl = previewUrl ?? serverAvatarUrl;

  return (
    <Container className="max-w-full space-y-6">
      <header>
        <h1 className="text-2xl font-bold text-slate-900 dark:text-white sm:text-3xl">
          {t("app.profile.title")}
        </h1>
        <p className="mt-1 text-sm text-slate-600 dark:text-slate-300">
          {t("app.profile.subtitle")}
        </p>
      </header>

      {/* Avatar + KYC badge */}
      <Card>
        <CardContent>
          <div className="flex flex-wrap items-center gap-6">
            <span className="relative inline-block">
              {avatarUrl ? (
                <Image
                  src={avatarUrl}
                  alt={`${firstName} ${lastName}`}
                  width={80}
                  height={80}
                  className="h-20 w-20 rounded-2xl object-cover shadow-soft"
                  unoptimized
                />
              ) : (
                <span className="grid h-20 w-20 place-items-center rounded-2xl bg-gradient-to-br from-brand-500 to-accent-500 text-xl font-bold text-white shadow-soft">
                  {initials}
                </span>
              )}
              <input
                ref={fileInputRef}
                type="file"
                accept="image/png,image/jpeg,image/webp"
                className="sr-only"
                onChange={handleImageChange}
                aria-hidden="true"
              />
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                className="absolute -bottom-1 -end-1 inline-flex h-8 w-8 items-center justify-center rounded-full border-2 border-white bg-slate-900 text-white shadow-soft transition hover:scale-105 dark:border-slate-900 dark:bg-white dark:text-slate-900"
                aria-label={t("app.profile.photoUpload")}
              >
                <Camera className="h-3.5 w-3.5" />
              </button>
            </span>

            <div className="flex-1">
              <p className="text-[length:var(--text-base-fixed)] font-semibold text-slate-900 dark:text-white">
                {t("app.profile.photoTitle")}
              </p>
              <p className="mt-0.5 text-xs text-slate-500 dark:text-slate-400">
                {t("app.profile.photoBody")}
              </p>
            </div>

            <span className={cn("inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-semibold", badge.cls)}>
              <BadgeIcon className="h-3.5 w-3.5" />
              {t(badge.key)}
            </span>
          </div>
        </CardContent>
      </Card>

      {/* Edit form */}
      <Card>
        <CardContent>
          {formError && (
            <p role="alert" className="mb-5 rounded-xl bg-rose-50 px-4 py-3 text-sm font-medium text-rose-700 dark:bg-rose-500/10 dark:text-rose-300">
              {formError}
            </p>
          )}
          <form onSubmit={onSubmit} className="space-y-5">
            <div className="grid gap-4 sm:grid-cols-2">
              <FormField
                label={t("app.profile.firstName")}
                placeholder="Enter first name"
                value={firstName}
                onChange={(e) => setFirstName(e.target.value)}
                autoComplete="given-name"
                disabled={isLoading}
                labelClassName={FIELD_LABEL_CLASSNAME}
              />
              <FormField
                label={t("app.profile.lastName")}
                placeholder="Enter last name"
                value={lastName}
                onChange={(e) => setLastName(e.target.value)}
                autoComplete="family-name"
                disabled={isLoading}
                labelClassName={FIELD_LABEL_CLASSNAME}
              />
            </div>

            <FormField
              label={t("app.profile.email")}
              type="email"
              placeholder="you@example.com"
              value={email}
              onChange={() => undefined}
              autoComplete="email"
              disabled
              labelClassName={FIELD_LABEL_CLASSNAME}
            />

            <FormField
              label={t("app.profile.phone")}
              type="tel"
              placeholder="Enter phone number"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              autoComplete="tel"
              disabled={isLoading}
              labelClassName={FIELD_LABEL_CLASSNAME}
            />

            <FormField
              label={t("app.profile.dateOfBirth")}
              type="date"
              value={dob}
              onChange={(e) => setDob(e.target.value)}
              autoComplete="bday"
              disabled={isLoading}
              labelClassName={FIELD_LABEL_CLASSNAME}
            />

            <CountrySelect
              label={t("app.profile.country")}
              countries={countries}
              value={country}
              onChange={setCountry}
              placeholder={t("app.profile.selectCountry")}
              disabled={isLoading}
            />

            <FormField
              label={t("app.profile.address")}
              placeholder="Enter your address"
              value={address}
              onChange={(e) => setAddress(e.target.value)}
              autoComplete="street-address"
              disabled={isLoading}
              labelClassName={FIELD_LABEL_CLASSNAME}
            />

            <div className="grid gap-4 sm:grid-cols-3">
              <FormField
                label={t("app.profile.city")}
                placeholder="Enter city"
                value={city}
                onChange={(e) => setCity(e.target.value)}
                autoComplete="address-level2"
                disabled={isLoading}
                labelClassName={FIELD_LABEL_CLASSNAME}
              />
              <FormField
                label={t("app.profile.state")}
                placeholder="Enter state"
                value={stateVal}
                onChange={(e) => setStateVal(e.target.value)}
                autoComplete="address-level1"
                disabled={isLoading}
                labelClassName={FIELD_LABEL_CLASSNAME}
              />
              <FormField
                label={t("app.profile.zip")}
                placeholder="Enter zip code"
                value={zip}
                onChange={(e) => setZip(e.target.value)}
                autoComplete="postal-code"
                disabled={isLoading}
                labelClassName={FIELD_LABEL_CLASSNAME}
              />
            </div>

            <div className="flex items-center gap-3">
              <Button type="submit" loading={isPending} disabled={isLoading || isPending}>
                {isPending ? t("app.profile.saving") : t("app.profile.save")}
              </Button>
              {savedAt && (
                <span className="inline-flex items-center gap-1.5 text-xs font-semibold text-accent-700 dark:text-accent-300">
                  <BadgeCheck className="h-3.5 w-3.5" />
                  {t("app.profile.success")}
                </span>
              )}
            </div>
          </form>
        </CardContent>
      </Card>
    </Container>
  );
}
