"use client";

import React, { useEffect, useRef, useState } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import {
  Clock,
  Eye,
  EyeOff,
  KeyRound,
  Trash2,
  TriangleAlert,
  Upload,
  User,
  UserCircle,
  XCircle,
} from "lucide-react";
import { Container } from "@/components/common/Container";
import { Card, CardContent } from "@/components/common/Card";
import { Button } from "@/components/common/Button";
import { Modal } from "@/components/app/Modal";
import { AgentProfileSkeleton } from "@/components/skeletons/AgentProfileSkeleton";
import {
  useAgentProfileInfo,
  useAgentUpdateProfile,
  useAgentUpdatePassword,
  useAgentDeleteAccount,
  type AgentProfileData,
} from "@/hooks/queries/useAgentProfile";
import { useAgentAuth } from "@/hooks/useAgentAuth";
import { notify } from "@/lib/notify";
import { cn } from "@/lib/utils";
import { useTranslation } from "@/hooks/useTranslation";

// ─── Shared input style ───────────────────────────────────────────────────────

const INPUT =
  "h-11 w-full rounded-2xl border border-slate-200 bg-white px-4 text-sm outline-none transition focus:border-brand-400 rtl:text-right dark:border-slate-700 dark:bg-slate-800/60 dark:text-white";

const LABEL = "block text-sm font-medium capitalize text-slate-500 dark:text-slate-400";

// ─── Personal info form ───────────────────────────────────────────────────────

function PersonalInfoForm({ profile }: { profile: AgentProfileData }) {
  const { t } = useTranslation();
  const { mutate: updateProfile, isPending } = useAgentUpdateProfile();
  const fileInputRef = useRef<HTMLInputElement>(null);

  const [form, setForm] = useState({
    firstname: profile.firstname || "",
    lastname: profile.lastname || "",
    store_name: profile.store_name || "",
    phone: profile.full_mobile || profile.mobile || "",
    country: profile.country || "",
    state: profile.state || "",
    city: profile.city || "",
    zip_code: profile.zip_code || "",
    address: profile.address || "",
  });
  const [selectedImage, setSelectedImage] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);

  function set(field: keyof typeof form) {
    return (e: React.ChangeEvent<HTMLInputElement>) => {
      setForm((prev) => ({ ...prev, [field]: e.target.value }));
    };
  }

  function handleSubmit(e: { preventDefault(): void }) {
    e.preventDefault();
    updateProfile(
      {
        ...form,
        ...(selectedImage ? { image: selectedImage } : {}),
      },
      {
        onSuccess: () => notify(t("agent.profile.profileUpdated"), "success"),
        onError: (err: Error) => notify(err.message || "Update failed", "error"),
      },
    );
  }

  function handleAvatarClick() {
    fileInputRef.current?.click();
  }

  function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 2 * 1024 * 1024) {
      notify(t("agent.profile.imageTooLarge"), "error");
      return;
    }
    setSelectedImage(file);
    setPreviewUrl(URL.createObjectURL(file));
  }

  const avatarUrl =
    previewUrl ||
    profile.agentImage ||
    `https://ui-avatars.com/api/?name=${encodeURIComponent(
      profile.firstname || profile.email || "Agent",
    )}&background=6366f1&color=fff`;

  return (
    <Card>
        <CardContent>
          {/* Avatar — centered */}
          <div className="flex flex-col items-center gap-3 pb-6 text-center">
            <div className="relative">
              <div className="h-20 w-20 overflow-hidden rounded-full ring-4 ring-brand-500/20">
                <Image
                  src={avatarUrl}
                  alt={profile.firstname || "Agent"}
                  width={80}
                  height={80}
                  className="h-full w-full object-cover"
                />
              </div>
              <button
                type="button"
                onClick={handleAvatarClick}
                aria-label="Change profile picture"
                className="absolute bottom-0 right-0 grid h-7 w-7 place-items-center rounded-full bg-brand-600 text-white shadow transition hover:bg-brand-700"
              >
                <Upload className="icon-sm" />
              </button>
              <input
                ref={fileInputRef}
                type="file"
                accept="image/*"
                className="hidden"
                onChange={(e) => {
                  handleFileChange(e);
                  e.target.value = "";
                }}
              />
            </div>
            <div>
              <p className="text-base font-bold text-slate-900 dark:text-white">
                {[profile.firstname, profile.lastname].filter(Boolean).join(" ") || "—"}
              </p>
              <p className="text-sm text-slate-500 dark:text-slate-400">{profile.email}</p>
              {profile.store_name && (
                <p className="mt-1 text-xs font-semibold text-brand-600 dark:text-brand-300">
                  {profile.store_name}
                </p>
              )}
            </div>
          </div>

          {/* Divider */}
          <div className="-mx-6 sm:-mx-7 border-t border-slate-100 dark:border-slate-800/60" />

          {/* Fields */}
          <div className="mt-6 flex items-center gap-2.5">
            <User className="h-4 w-4 shrink-0 text-slate-400" />
            <h2 className="text-[length:var(--text-lg-fixed)] font-bold text-slate-900 dark:text-white">
              {t("agent.profile.personalInfo")}
            </h2>
          </div>

          <form onSubmit={handleSubmit} className="mt-6 space-y-6">
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="flex flex-col gap-1.5">
                <label htmlFor="firstname" className={LABEL}>{t("agent.profile.firstNameLabel")} <span className="text-rose-500">*</span></label>
                <input id="firstname" type="text" placeholder="Enter first name" value={form.firstname} onChange={set("firstname")} required className={INPUT} />
              </div>
              <div className="flex flex-col gap-1.5">
                <label htmlFor="lastname" className={LABEL}>{t("agent.profile.lastNameLabel")} <span className="text-rose-500">*</span></label>
                <input id="lastname" type="text" placeholder="Enter last name" value={form.lastname} onChange={set("lastname")} required className={INPUT} />
              </div>
            </div>

            <div className="flex flex-col gap-1.5">
              <label htmlFor="store_name" className={LABEL}>{t("agent.profile.storeNameLabel")} <span className="text-rose-500">*</span></label>
              <input id="store_name" type="text" placeholder="Enter store name" value={form.store_name} onChange={set("store_name")} required className={INPUT} />
            </div>

            <div className="flex flex-col gap-1.5">
              <label className={LABEL}>{t("agent.profile.emailLabel")}</label>
              <input
                type="email"
                value={profile.email}
                placeholder="you@example.com"
                readOnly
                className={cn(INPUT, "cursor-default opacity-60")}
              />
            </div>

            <div className="flex flex-col gap-1.5">
              <label htmlFor="phone" className={LABEL}>{t("agent.profile.phoneLabel")} <span className="text-rose-500">*</span></label>
              <input id="phone" type="tel" placeholder="Enter phone number" value={form.phone} onChange={set("phone")} required className={INPUT} />
            </div>

            <div className="grid gap-4 sm:grid-cols-2">
              <div className="flex flex-col gap-1.5">
                <label htmlFor="country" className={LABEL}>{t("agent.profile.countryLabel")} <span className="text-rose-500">*</span></label>
                <input id="country" type="text" placeholder="Enter country" value={form.country} onChange={set("country")} required className={INPUT} />
              </div>
              <div className="flex flex-col gap-1.5">
                <label htmlFor="city" className={LABEL}>{t("agent.profile.cityLabel")} <span className="text-rose-500">*</span></label>
                <input id="city" type="text" placeholder="Enter city" value={form.city} onChange={set("city")} required className={INPUT} />
              </div>
            </div>

            <div className="grid gap-4 sm:grid-cols-2">
              <div className="flex flex-col gap-1.5">
                <label htmlFor="state" className={LABEL}>{t("agent.profile.stateLabel")} <span className="text-rose-500">*</span></label>
                <input id="state" type="text" placeholder="Enter state" value={form.state} onChange={set("state")} required className={INPUT} />
              </div>
              <div className="flex flex-col gap-1.5">
                <label htmlFor="zip_code" className={LABEL}>{t("agent.profile.zipLabel")} <span className="text-rose-500">*</span></label>
                <input id="zip_code" type="text" placeholder="Enter zip code" value={form.zip_code} onChange={set("zip_code")} required className={INPUT} />
              </div>
            </div>

            <div className="flex flex-col gap-1.5">
              <label htmlFor="address" className={LABEL}>{t("agent.profile.addressLabel")} <span className="text-rose-500">*</span></label>
              <input id="address" type="text" placeholder="Enter full address" value={form.address} onChange={set("address")} required className={INPUT} />
            </div>

            <div>
              <Button type="submit" size="md" disabled={isPending}>
                {isPending ? t("agent.profile.saving") : t("agent.profile.saveChanges")}
              </Button>
            </div>
          </form>
        </CardContent>
    </Card>
  );
}

// ─── Shared password input ────────────────────────────────────────────────────

type PwForm = { current_password: string; password: string; password_confirmation: string };
type PwShow = { current: boolean; next: boolean; confirm: boolean };

function PasswordInput({
  id,
  label,
  placeholder,
  value,
  onChange,
  visible,
  onToggle,
}: {
  id: string;
  label: string;
  placeholder?: string;
  value: string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  visible: boolean;
  onToggle: () => void;
}) {
  return (
    <div className="flex flex-col gap-1.5">
      <label htmlFor={id} className={LABEL}>{label}</label>
      <div className="relative">
        <input
          id={id}
          type={visible ? "text" : "password"}
          value={value}
          placeholder={placeholder}
          onChange={onChange}
          className={cn(INPUT, "pe-11")}
        />
        <button
          type="button"
          onClick={onToggle}
          className="absolute end-3 top-1/2 -translate-y-1/2 text-slate-400 transition hover:text-slate-600 dark:hover:text-slate-200"
        >
          {visible ? <EyeOff className="icon-md" /> : <Eye className="icon-md" />}
        </button>
      </div>
    </div>
  );
}

// ─── Change password form ─────────────────────────────────────────────────────

function PasswordForm() {
  const { t } = useTranslation();
  const { mutate: updatePassword, isPending } = useAgentUpdatePassword();

  const [form, setForm] = useState<PwForm>({
    current_password: "",
    password: "",
    password_confirmation: "",
  });
  const [show, setShow] = useState<PwShow>({
    current: false,
    next: false,
    confirm: false,
  });

  function set(field: keyof PwForm) {
    return (e: React.ChangeEvent<HTMLInputElement>) =>
      setForm((prev) => ({ ...prev, [field]: e.target.value }));
  }

  function toggle(field: keyof PwShow) {
    setShow((prev) => ({ ...prev, [field]: !prev[field] }));
  }

  function handleSubmit(e: { preventDefault(): void }) {
    e.preventDefault();
    if (form.password !== form.password_confirmation) {
      notify(t("agent.profile.passwordMismatch"), "error");
      return;
    }
    updatePassword(form, {
      onSuccess: () => {
        notify(t("agent.profile.passwordUpdated"), "success");
        setForm({ current_password: "", password: "", password_confirmation: "" });
      },
      onError: (err: Error) => notify(err.message || "Password update failed", "error"),
    });
  }

  return (
    <Card>
      <CardContent>
        <div className="flex items-center gap-2.5">
          <KeyRound className="h-4.5 w-4.5 text-slate-400" />
          <h2 className="text-[length:var(--text-lg-fixed)] font-bold text-slate-900 dark:text-white">{t("agent.profile.changePassword")}</h2>
        </div>

        <form onSubmit={handleSubmit} className="mt-5 space-y-6">
          <PasswordInput
            id="current_password"
            label={t("agent.profile.currentPasswordLabel")}
            placeholder="Enter current password"
            value={form.current_password}
            onChange={set("current_password")}
            visible={show.current}
            onToggle={() => toggle("current")}
          />
          <div className="grid gap-4 sm:grid-cols-2">
            <PasswordInput
              id="password"
              label={t("agent.profile.newPasswordLabel")}
              placeholder="Enter new password"
              value={form.password}
              onChange={set("password")}
              visible={show.next}
              onToggle={() => toggle("next")}
            />
            <PasswordInput
              id="password_confirmation"
              label={t("agent.profile.confirmPasswordLabel")}
              placeholder="Re-enter new password"
              value={form.password_confirmation}
              onChange={set("password_confirmation")}
              visible={show.confirm}
              onToggle={() => toggle("confirm")}
            />
          </div>
          <div className="pt-1">
            <Button type="submit" size="md" disabled={isPending || !form.current_password || !form.password}>
              {isPending ? t("agent.profile.updating") : t("agent.profile.updatePassword")}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}

// ─── Danger zone ──────────────────────────────────────────────────────────────

function DangerZone() {
  const { t } = useTranslation();
  const { mutate: deleteAccount, isPending } = useAgentDeleteAccount();
  const { signOut } = useAgentAuth();
  const router = useRouter();
  const [modalOpen, setModalOpen] = useState(false);
  const [timer, setTimer] = useState(10);
  const [typedValue, setTypedValue] = useState("");
  const [debouncedValue, setDebouncedValue] = useState("");

  useEffect(() => {
    let interval: ReturnType<typeof setInterval>;
    if (modalOpen && timer > 0) {
      interval = setInterval(() => {
        setTimer((prev) => (prev > 0 ? prev - 1 : 0));
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [modalOpen, timer]);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(typedValue);
    }, 300);
    return () => clearTimeout(handler);
  }, [typedValue]);

  function handleOpen() {
    setTimer(10);
    setTypedValue("");
    setDebouncedValue("");
    setModalOpen(true);
  }

  function handleClose() {
    if (isPending) return;
    setModalOpen(false);
    setTimer(10);
    setTypedValue("");
    setDebouncedValue("");
  }

  function handleDelete() {
    deleteAccount(undefined, {
      onSuccess: () => {
        setModalOpen(false);
        signOut();
        router.push("/agent/login");
      },
      onError: (err: Error) => notify(err.message || "Failed to delete account", "error"),
    });
  }

  const isConfirmed = timer === 0 && (debouncedValue.trim() === "yes" || debouncedValue.trim() === "YES");

  return (
    <>
      <Card className="border border-rose-500/40 shadow-[0_0_20px_rgba(244,63,94,0.15)] dark:border-rose-500/40 dark:shadow-[0_0_20px_rgba(244,63,94,0.25)]">
        <CardContent>
          <h2 className="text-[length:var(--text-lg-fixed)] font-bold text-slate-900 dark:text-white">{t("agent.profile.dangerZone")}</h2>
          <p className="mt-1.5 text-sm text-slate-500 dark:text-slate-400">
            {t("agent.profile.dangerSubtitle")}
          </p>

          <div className="mt-5">
            <Button
              size="md"
              onClick={handleOpen}
              className="border-rose-200 bg-rose-50 text-rose-700 hover:bg-rose-100 dark:border-rose-500/30 dark:bg-rose-500/10 dark:text-rose-400 dark:hover:bg-rose-500/20"
            >
              <Trash2 className="me-1.5 h-4 w-4" />
              {t("agent.profile.deleteAccount")}
            </Button>
          </div>
        </CardContent>
      </Card>

      <Modal open={modalOpen} onClose={handleClose} title={t("agent.profile.deleteModalTitle")} size="md">
        <div className="space-y-5">
          <div className="flex items-start gap-3.5 rounded-2xl border border-rose-200 bg-rose-50/80 p-4 dark:border-rose-500/30 dark:bg-rose-500/10">
            <TriangleAlert className="mt-0.5 h-5 w-5 shrink-0 text-rose-600 dark:text-rose-400" />
            <div className="space-y-1">
              <p className="text-sm font-bold text-rose-800 dark:text-rose-300">{t("agent.profile.deleteModalBadge")}</p>
              <p className="text-xs sm:text-sm text-rose-700/90 dark:text-rose-400/90 leading-relaxed">
                {t("agent.profile.deleteModalBody")}
              </p>
            </div>
          </div>

          <div className="flex items-center justify-between rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 dark:border-slate-800 dark:bg-slate-800/40">
            <div className="flex items-center gap-2.5">
              <Clock className={cn("icon-md", timer > 0 ? "text-amber-500 animate-spin" : "text-emerald-500")} />
              <span className="text-xs sm:text-sm font-semibold text-slate-700 dark:text-slate-300">
                {t("agent.profile.securityCooldown")}
              </span>
            </div>
            <span className={cn(
              "rounded-full px-3 py-1 text-xs font-bold transition-all",
              timer > 0 
                ? "bg-amber-100 text-amber-800 dark:bg-amber-500/20 dark:text-amber-300" 
                : "bg-emerald-100 text-emerald-800 dark:bg-emerald-500/20 dark:text-emerald-300"
            )}>
              {timer > 0 ? t("agent.profile.waitSeconds").replace("{n}", String(timer)) : t("agent.profile.unlocked")}
            </span>
          </div>

          <div className="flex flex-col gap-1.5 pt-1">
            <label htmlFor="confirm_delete_input" className="block text-sm font-semibold text-slate-700 dark:text-slate-200">
              {t("agent.profile.confirmInputLabel")}
            </label>
            <input
              id="confirm_delete_input"
              type="text"
              placeholder={t("agent.profile.confirmInputPlaceholder")}
              disabled={timer > 0 || isPending}
              value={typedValue}
              onChange={(e) => setTypedValue(e.target.value)}
              className={cn(
                "h-11 w-full rounded-2xl border bg-white px-4 text-sm font-bold text-slate-900 outline-none transition placeholder:font-normal placeholder:text-slate-400 dark:bg-slate-900 dark:text-white",
                timer > 0 
                  ? "border-slate-200 bg-slate-100 opacity-60 cursor-not-allowed dark:border-slate-800 dark:bg-slate-800/50" 
                  : "border-slate-300 focus:border-rose-500 focus:shadow-glow-sm dark:border-slate-700 dark:focus:border-rose-500"
              )}
            />
          </div>

          <div className="flex items-center justify-end gap-3 pt-4 border-t border-slate-100 dark:border-slate-800">
            <Button
              type="button"
              size="md"
              variant="outline"
              disabled={isPending}
              onClick={handleClose}
            >
              {t("agent.profile.cancel")}
            </Button>
            <Button
              type="button"
              size="md"
              disabled={!isConfirmed || isPending}
              onClick={handleDelete}
              className={cn(
                "transition-all duration-200 font-bold",
                isConfirmed 
                  ? "bg-rose-600 text-white hover:bg-rose-700 shadow-soft hover:shadow-glow" 
                  : "bg-slate-200 text-slate-400 cursor-not-allowed dark:bg-slate-800 dark:text-slate-600"
              )}
            >
              {isPending ? t("agent.profile.deleting") : t("agent.profile.confirmDelete")}
            </Button>
          </div>
        </div>
      </Modal>
    </>
  );
}

// ─── Main view ────────────────────────────────────────────────────────────────

export function AgentProfileView() {
  const { t } = useTranslation();
  const { data, isLoading, isError } = useAgentProfileInfo();

  if (isLoading) return <AgentProfileSkeleton />;

  if (isError) {
    return (
      <Container className="max-w-full pb-10">
        <div className="flex flex-col items-center gap-4 rounded-3xl border border-rose-200 bg-rose-50 p-16 text-center dark:border-rose-500/20 dark:bg-rose-500/10">
          <XCircle className="h-10 w-10 text-rose-500" />
          <div>
            <p className="font-semibold text-slate-900 dark:text-white">{t("agent.profile.failedToLoad")}</p>
            <p className="mt-1 text-sm text-slate-500">{t("agent.profile.failedSubtitle")}</p>
          </div>
        </div>
      </Container>
    );
  }

  const profile = data as AgentProfileData;

  return (
    <Container className="max-w-full space-y-6 pb-10">
      {/* Page header */}
      <header className="flex items-center gap-4">
        <div className="icon-box-md grid place-items-center rounded-2xl bg-gradient-to-br from-brand-500 to-accent-500 text-white shadow-lg">
          <UserCircle className="icon-xl" />
        </div>
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white">{t("agent.profile.title")}</h1>
          <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">
            {t("agent.profile.subtitle")}
          </p>
        </div>
      </header>

      <PersonalInfoForm profile={profile} />
      <PasswordForm />
      <DangerZone />
    </Container>
  );
}
