import { useState, useRef } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { useForm } from "react-hook-form";
import { useQueryClient } from "@tanstack/react-query";
import {
  FiArrowLeft, FiUser, FiLock, FiCamera, FiImage,
  FiMail, FiAtSign, FiShield, FiAlertTriangle, FiTrash2,
} from "react-icons/fi";
import { useAuth } from "@/hooks/useAuth";
import { useTurnstile } from "@/hooks/useTurnstile";
import { privateApi } from "@/api/privateClient";
import { mediaUrl } from "@/utils/mediaUrl";
import Avatar from "@/components/ui/Avatar";
import Button from "@/components/ui/Button";
import Spinner from "@/components/ui/Spinner";
import FormErrorBanner from "@/components/ui/FormErrorBanner";
import { applyServerErrors } from "@/utils/formErrors";

type Tab = "profile" | "account" | "security";

interface ProfileForm {
  first_name: string;
  last_name: string;
  city: string;
  phone_number: string;
}

interface UsernameForm { new_username: string }
interface EmailForm { current_password: string; new_email: string }
interface PasswordForm { current_password: string; new_password: string; confirm_password: string }

// ── Reusable section header ─────────────────────────────────────
function Section({ title, subtitle }: { title: string; subtitle?: string }) {
  return (
    <div className="mb-4">
      <h2 className="text-sm font-semibold text-brand-text">{title}</h2>
      {subtitle && <p className="mt-0.5 text-xs text-brand-text/50">{subtitle}</p>}
    </div>
  );
}

// ── Feedback row ────────────────────────────────────────────────
function Success({ msg }: { msg: string }) {
  return (
    <div className="rounded-xl bg-green-500/10 border border-green-500/20 px-3 py-2 text-sm text-green-400">
      {msg}
    </div>
  );
}

// ── Delete account confirmation form (own component so useTurnstile mounts fresh) ──
function DeleteAccountForm({
  inputClass,
  onCancel,
  onDeleted,
}: {
  inputClass: string;
  onCancel: () => void;
  onDeleted: () => void;
}) {
  const navigate = useNavigate();
  const { refreshUser } = useAuth() as any;
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string>();
  const [submitting, setSubmitting] = useState(false);
  const { containerRef, token, enabled } = useTurnstile();

  async function handleDelete() {
    if (!password || !token) return;
    setError(undefined);
    setSubmitting(true);
    try {
      await privateApi.post("/api/account/delete/", {
        current_password: password,
        turnstile_token: token,
      });
      await refreshUser?.();
      navigate("/");
      onDeleted();
    } catch (err: any) {
      setError(
        err?.response?.data?.detail ??
        err?.response?.data?.current_password ??
        "Chyba. Zkuste to znovu."
      );
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="flex flex-col gap-3">
      <p className="text-xs text-brand-text/60">
        Pro potvrzení zadejte své heslo. Účet bude okamžitě deaktivován a budete odhlášeni.
      </p>
      {error && <p className="text-xs text-red-400">{error}</p>}
      <input
        type="password"
        className={inputClass + " border-red-500/30 focus:border-red-400"}
        placeholder="Vaše heslo"
        autoComplete="current-password"
        value={password}
        onChange={e => setPassword(e.target.value)}
      />
      {enabled && <div ref={containerRef} className="flex justify-center" />}
      <div className="flex gap-2">
        <button
          type="button"
          onClick={onCancel}
          className="flex-1 rounded-xl border border-brand-lines/20 bg-brand-bgLight/30 px-3 py-2 text-xs font-medium text-brand-text/70 hover:bg-brand-bgLight/50 transition-colors"
        >
          Zrušit
        </button>
        <button
          type="button"
          onClick={handleDelete}
          disabled={submitting || !password || !token}
          className="flex-1 flex items-center justify-center gap-1.5 rounded-xl bg-red-600/80 px-3 py-2 text-xs font-semibold text-white hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          {submitting ? <Spinner size={12} /> : <FiTrash2 size={12} />}
          {submitting ? "Mažu…" : "Potvrdit smazání"}
        </button>
      </div>
    </div>
  );
}

export default function AccountSettingsPage() {
  const { t } = useTranslation("social");
  const { user, refreshUser } = useAuth() as any;
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [tab, setTab] = useState<Tab>("profile");

  const inputClass =
    "w-full rounded-xl border border-brand-lines/25 bg-brand-bgLight/40 px-3 py-2 text-sm text-brand-text " +
    "placeholder:text-brand-text/30 focus:outline-none focus:border-brand-accent disabled:opacity-50";

  // ── Profile ───────────────────────────────────────────────────
  const [profileSuccess, setProfileSuccess] = useState(false);
  const [profileError, setProfileError] = useState<string>();
  const profileForm = useForm<ProfileForm>({
    defaultValues: {
      first_name: user?.first_name ?? "",
      last_name: user?.last_name ?? "",
      city: user?.city ?? "",
      phone_number: user?.phone_number ?? "",
    },
  });
  const { register: rP, handleSubmit: hP, formState: { isSubmitting: pSubmit } } = profileForm;

  async function onProfileSubmit(values: ProfileForm) {
    setProfileError(undefined);
    setProfileSuccess(false);
    try {
      await privateApi.patch(`/api/account/users/${user.id}/`, values);
      setProfileSuccess(true);
      await queryClient.invalidateQueries({ queryKey: ["account"] });
      await refreshUser?.();
    } catch (err) {
      setProfileError(applyServerErrors(profileForm, err));
    }
  }

  // ── Avatar ────────────────────────────────────────────────────
  const avatarRef = useRef<HTMLInputElement>(null);
  const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
  const [avatarUploading, setAvatarUploading] = useState(false);
  async function handleAvatar(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setAvatarPreview(URL.createObjectURL(file));
    setAvatarUploading(true);
    try {
      const fd = new FormData();
      fd.append("avatar", file);
      await privateApi.patch(`/api/account/users/${user.id}/`, fd);
      await queryClient.invalidateQueries({ queryKey: ["account"] });
      await refreshUser?.();
    } finally { setAvatarUploading(false); e.target.value = ""; }
  }

  // ── Banner ────────────────────────────────────────────────────
  const bannerRef = useRef<HTMLInputElement>(null);
  const [bannerPreview, setBannerPreview] = useState<string | null>(null);
  const [bannerUploading, setBannerUploading] = useState(false);
  async function handleBanner(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setBannerPreview(URL.createObjectURL(file));
    setBannerUploading(true);
    try {
      const fd = new FormData();
      fd.append("banner", file);
      await privateApi.patch(`/api/account/users/${user.id}/`, fd);
      await queryClient.invalidateQueries({ queryKey: ["account"] });
      await refreshUser?.();
    } finally { setBannerUploading(false); e.target.value = ""; }
  }

  // ── Username change ───────────────────────────────────────────
  const [usernameSuccess, setUsernameSuccess] = useState(false);
  const [usernameError, setUsernameError] = useState<string>();
  const [daysRemaining, setDaysRemaining] = useState<number | null>(null);
  const usernameForm = useForm<UsernameForm>({ defaultValues: { new_username: "" } });
  const { register: rU, handleSubmit: hU, formState: { isSubmitting: uSubmit }, reset: resetUsername } = usernameForm;
  const { containerRef: tUsernameRef, token: tUsernameToken, enabled: turnstileEnabled, reset: resetTUsername } = useTurnstile();

  async function onUsernameSubmit(values: UsernameForm) {
    if (!tUsernameToken) return;
    setUsernameError(undefined);
    setUsernameSuccess(false);
    setDaysRemaining(null);
    try {
      await privateApi.post("/api/account/change-username/", {
        new_username: values.new_username,
        turnstile_token: tUsernameToken,
      });
      setUsernameSuccess(true);
      resetUsername();
      await refreshUser?.();
    } catch (err: any) {
      const days = err?.response?.data?.days_remaining;
      if (days) setDaysRemaining(days);
      setUsernameError(applyServerErrors(usernameForm, err));
      resetTUsername();
    }
  }

  // ── Email change ──────────────────────────────────────────────
  const [emailSuccess, setEmailSuccess] = useState(false);
  const [emailError, setEmailError] = useState<string>();
  const emailForm = useForm<EmailForm>({ defaultValues: { current_password: "", new_email: "" } });
  const { register: rE, handleSubmit: hE, formState: { isSubmitting: eSubmit }, reset: resetEmail } = emailForm;
  const { containerRef: tEmailRef, token: tEmailToken, reset: resetTEmail } = useTurnstile();

  async function onEmailSubmit(values: EmailForm) {
    if (!tEmailToken) return;
    setEmailError(undefined);
    setEmailSuccess(false);
    try {
      await privateApi.post("/api/account/change-email/", {
        current_password: values.current_password,
        new_email: values.new_email,
        turnstile_token: tEmailToken,
      });
      setEmailSuccess(true);
      resetEmail();
    } catch (err) {
      setEmailError(applyServerErrors(emailForm, err));
      resetTEmail();
    }
  }

  // ── Account deletion ─────────────────────────────────────────
  const [deleteOpen, setDeleteOpen] = useState(false);

  // ── Password change ───────────────────────────────────────────
  const [passwordSuccess, setPasswordSuccess] = useState(false);
  const [passwordError, setPasswordError] = useState<string>();
  const passwordForm = useForm<PasswordForm>({
    defaultValues: { current_password: "", new_password: "", confirm_password: "" },
  });
  const {
    register: rPw, handleSubmit: hPw,
    formState: { isSubmitting: pwSubmit },
    reset: resetPassword, setError: setPwError,
  } = passwordForm;

  async function onPasswordSubmit(values: PasswordForm) {
    setPasswordError(undefined);
    setPasswordSuccess(false);
    if (values.new_password !== values.confirm_password) {
      setPwError("confirm_password", { message: t("accountSettings.passwordMismatch") });
      return;
    }
    try {
      await privateApi.post("/api/account/password-change/", {
        current_password: values.current_password,
        new_password: values.new_password,
      });
      setPasswordSuccess(true);
      resetPassword();
    } catch (err) {
      setPasswordError(applyServerErrors(passwordForm, err));
    }
  }

  const displayName = [user?.first_name, user?.last_name].filter(Boolean).join(" ") || user?.username || "?";
  const avatarSrc = avatarPreview ?? mediaUrl((user as any)?.avatar);
  const bannerSrc = bannerPreview ?? mediaUrl((user as any)?.banner);

  const tabs: { id: Tab; label: string; icon: React.ReactNode }[] = [
    { id: "profile",  label: "Profil",       icon: <FiUser size={15} /> },
    { id: "account",  label: "Účet",          icon: <FiAtSign size={15} /> },
    { id: "security", label: "Zabezpečení",   icon: <FiShield size={15} /> },
  ];

  const tabClass = (active: boolean) =>
    [
      "flex items-center gap-2 rounded-xl px-3 py-2 text-sm font-medium transition-colors w-full text-left",
      active
        ? "bg-brand-lines/15 text-brand-text"
        : "text-brand-text/55 hover:bg-brand-lines/10 hover:text-brand-text",
    ].join(" ");

  return (
    <div>
      <header className="sticky top-0 z-10 flex items-center gap-3 border-b border-brand-lines/10 bg-brand-bg/80 px-4 py-3 backdrop-blur">
        <button
          type="button"
          onClick={() => navigate(-1)}
          className="rounded-full p-1 text-brand-text hover:bg-brand-lines/10"
        >
          <FiArrowLeft size={20} />
        </button>
        <h1 className="text-lg font-bold text-brand-text">Nastavení účtu</h1>
      </header>

      <div className="flex">
        {/* Sidebar */}
        <nav className="w-[180px] shrink-0 border-r border-brand-lines/10 p-3 flex flex-col gap-2">
          {tabs.map(({ id, label, icon }) => (
            <button key={id} type="button" className={tabClass(tab === id)} onClick={() => setTab(id)}>
              {icon} {label}
            </button>
          ))}
        </nav>

        {/* Content */}
        <div className="flex-1 p-6 max-w-lg flex flex-col gap-8">

          {/* ── Profil ── */}
          {tab === "profile" && (
            <>
              <Section title="Fotografie" subtitle="Profilová fotka a banner viditelné ostatním uživatelům." />

              {/* Banner + avatar */}
              <div className="relative mb-6">
                <div
                  className="group relative h-28 w-full cursor-pointer overflow-hidden rounded-2xl bg-gradient-to-br from-brand-bgLight to-brand-lines/20"
                  onClick={() => bannerRef.current?.click()}
                >
                  {bannerSrc && <img src={bannerSrc} alt="" className="h-full w-full object-cover" />}
                  <div className="absolute inset-0 flex items-center justify-center bg-black/20 transition-colors group-hover:bg-black/40">
                    {bannerUploading ? <Spinner size={22} /> : (
                      <div className="flex flex-col items-center gap-1 opacity-50 group-hover:opacity-100 transition-opacity">
                        <FiImage size={20} className="text-white" />
                        <span className="text-xs text-white/90">Změnit banner</span>
                      </div>
                    )}
                  </div>
                </div>
                <input ref={bannerRef} type="file" accept="image/*" className="hidden" onChange={handleBanner} />

                <div className="absolute -bottom-8 left-4">
                  <div className="relative rounded-full ring-4 ring-brand-bg">
                    <Avatar name={displayName} src={avatarSrc} size={64} />
                    {avatarUploading && (
                      <div className="absolute inset-0 flex items-center justify-center rounded-full bg-black/50">
                        <Spinner size={16} />
                      </div>
                    )}
                    <button
                      type="button"
                      onClick={() => avatarRef.current?.click()}
                      className="absolute -bottom-1 -right-1 flex h-6 w-6 items-center justify-center rounded-full bg-brand-accent text-white shadow hover:opacity-90"
                    >
                      <FiCamera size={11} />
                    </button>
                  </div>
                  <input ref={avatarRef} type="file" accept="image/*" className="hidden" onChange={handleAvatar} />
                </div>
              </div>

              <p className="text-xs text-brand-text/35 -mt-4">Maximální velikost souboru: 5 MB. Formáty: JPG, PNG, WebP.</p>

              <hr className="border-brand-lines/10" />

              <Section title="Základní informace" subtitle="Zobrazené jméno a kontaktní údaje." />

              <form onSubmit={hP(onProfileSubmit)} className="flex flex-col gap-4">
                <FormErrorBanner message={profileError} />
                {profileSuccess && <Success msg="Profil byl uložen." />}

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="mb-1 block text-xs font-medium text-brand-text/65">Jméno</label>
                    <input className={inputClass} placeholder="Jan" {...rP("first_name")} />
                  </div>
                  <div>
                    <label className="mb-1 block text-xs font-medium text-brand-text/65">Příjmení</label>
                    <input className={inputClass} placeholder="Novák" {...rP("last_name")} />
                  </div>
                </div>

                <div>
                  <label className="mb-1 block text-xs font-medium text-brand-text/65">Město</label>
                  <input className={inputClass} placeholder="Praha" {...rP("city")} />
                </div>

                <div>
                  <label className="mb-1 block text-xs font-medium text-brand-text/65">Telefon</label>
                  <input className={inputClass} placeholder="+420 ..." {...rP("phone_number")} />
                </div>

                <Button type="submit" disabled={pSubmit} leftIcon={pSubmit ? <Spinner size={14} /> : undefined}>
                  {pSubmit ? "Ukládám…" : "Uložit profil"}
                </Button>
              </form>
            </>
          )}

          {/* ── Účet ── */}
          {tab === "account" && (
            <>
              {/* Username */}
              <div>
                <Section
                  title="Uživatelské jméno"
                  subtitle={`Aktuálně: @${user?.username} · Lze měnit jednou za 30 dní.`}
                />
                <form onSubmit={hU(onUsernameSubmit)} className="flex flex-col gap-3">
                  <FormErrorBanner message={usernameError} />
                  {daysRemaining !== null && (
                    <div className="rounded-xl bg-amber-500/10 border border-amber-500/20 px-3 py-2 text-sm text-amber-400">
                      Příliš brzy. Zkuste to za {daysRemaining} {daysRemaining === 1 ? "den" : "dní"}.
                    </div>
                  )}
                  {usernameSuccess && <Success msg="Uživatelské jméno bylo změněno." />}

                  <div>
                    <label className="mb-1 block text-xs font-medium text-brand-text/65">Nové uživatelské jméno</label>
                    <input
                      className={inputClass}
                      placeholder={user?.username}
                      {...rU("new_username", { required: true, minLength: 3 })}
                    />
                    {usernameForm.formState.errors.new_username && (
                      <p className="mt-1 text-xs text-red-400">Minimálně 3 znaky.</p>
                    )}
                  </div>

                  {turnstileEnabled && <div ref={tUsernameRef} className="flex justify-center" />}

                  <Button
                    type="submit"
                    variant="secondary"
                    disabled={uSubmit || !tUsernameToken}
                    leftIcon={uSubmit ? <Spinner size={14} /> : undefined}
                  >
                    {uSubmit ? "Ukládám…" : "Změnit jméno"}
                  </Button>
                </form>
              </div>

              <hr className="border-brand-lines/10" />

              {/* Email */}
              <div>
                <Section
                  title="E-mailová adresa"
                  subtitle={`Aktuálně: ${user?.email} · Po odeslání potvrďte novou adresu kliknutím na odkaz v e-mailu.`}
                />
                <form onSubmit={hE(onEmailSubmit)} className="flex flex-col gap-4">
                  <FormErrorBanner message={emailError} />
                  {emailSuccess && <Success msg="Ověřovací e-mail byl odeslán na novou adresu." />}

                  <div>
                    <label className="mb-1 block text-xs font-medium text-brand-text/65">Stávající heslo</label>
                    <input
                      className={inputClass}
                      placeholder="••••••••"
                      autoComplete="current-password"
                      {...rE("current_password", { required: true })}
                      type="password"
                    />
                    {emailForm.formState.errors.current_password && (
                      <p className="mt-1 text-xs text-red-400">Povinné pole.</p>
                    )}
                  </div>

                  <div>
                    <label className="mb-1 block text-xs font-medium text-brand-text/65">Nová e-mailová adresa</label>
                    <input
                      className={inputClass}
                      placeholder="nova@adresa.cz"
                      autoComplete="email"
                      inputMode="email"
                      {...rE("new_email", { required: true })}
                      type="email"
                    />
                    {emailForm.formState.errors.new_email && (
                      <p className="mt-1 text-xs text-red-400">Povinné pole.</p>
                    )}
                  </div>

                  {turnstileEnabled && <div ref={tEmailRef} className="flex justify-center" />}

                  <Button
                    type="submit"
                    variant="secondary"
                    disabled={eSubmit || !tEmailToken}
                    leftIcon={eSubmit ? <Spinner size={14} /> : <FiMail size={14} />}
                  >
                    {eSubmit ? "Odesílám…" : "Odeslat ověřovací e-mail"}
                  </Button>
                </form>
              </div>
            </>
          )}

          {/* ── Zabezpečení ── */}
          {tab === "security" && (
            <div className="flex flex-col gap-8">

              {/* Password */}
              <div>
                <Section title="Změna hesla" subtitle="Heslo musí mít alespoň 8 znaků, velké i malé písmeno a číslici." />
                <form onSubmit={hPw(onPasswordSubmit)} className="flex flex-col gap-4">
                  <FormErrorBanner message={passwordError} />
                  {passwordSuccess && <Success msg="Heslo bylo úspěšně změněno." />}

                  <div>
                    <label className="mb-1 block text-xs font-medium text-brand-text/65">Stávající heslo</label>
                    <input
                      type="password"
                      className={inputClass}
                      placeholder="••••••••"
                      autoComplete="current-password"
                      {...rPw("current_password", { required: true })}
                    />
                    {passwordForm.formState.errors.current_password && (
                      <p className="mt-1 text-xs text-red-400">Povinné pole.</p>
                    )}
                  </div>

                  <div>
                    <label className="mb-1 block text-xs font-medium text-brand-text/65">Nové heslo</label>
                    <input
                      type="password"
                      className={inputClass}
                      placeholder="••••••••"
                      autoComplete="new-password"
                      {...rPw("new_password", { required: true })}
                    />
                    {passwordForm.formState.errors.new_password && (
                      <p className="mt-1 text-xs text-red-400">Povinné pole.</p>
                    )}
                  </div>

                  <div>
                    <label className="mb-1 block text-xs font-medium text-brand-text/65">Potvrdit nové heslo</label>
                    <input
                      type="password"
                      className={inputClass}
                      placeholder="••••••••"
                      autoComplete="new-password"
                      {...rPw("confirm_password", { required: true })}
                    />
                    {passwordForm.formState.errors.confirm_password && (
                      <p className="mt-1 text-xs text-red-400">
                        {passwordForm.formState.errors.confirm_password.message ?? "Povinné pole."}
                      </p>
                    )}
                  </div>

                  <Button
                    type="submit"
                    disabled={pwSubmit}
                    leftIcon={pwSubmit ? <Spinner size={14} /> : <FiLock size={14} />}
                  >
                    {pwSubmit ? "Ukládám…" : "Změnit heslo"}
                  </Button>
                </form>
              </div>

              {/* Danger zone */}
              <div className="rounded-2xl border border-red-500/20 bg-red-500/5 p-4 flex flex-col gap-4">
                <div className="flex items-center gap-2">
                  <FiAlertTriangle size={15} className="text-red-400 shrink-0" />
                  <span className="text-sm font-semibold text-red-400">Nebezpečná zóna</span>
                </div>

                {!deleteOpen ? (
                  <div className="flex items-center justify-between gap-4">
                    <p className="text-xs text-brand-text/50">
                      Trvale deaktivuje váš účet. Tato akce je nevratná.
                    </p>
                    <button
                      type="button"
                      onClick={() => setDeleteOpen(true)}
                      className="shrink-0 flex items-center gap-1.5 rounded-xl border border-red-500/30 bg-red-500/10 px-3 py-1.5 text-xs font-medium text-red-400 hover:bg-red-500/20 transition-colors"
                    >
                      <FiTrash2 size={13} /> Smazat účet
                    </button>
                  </div>
                ) : (
                  <DeleteAccountForm
                    inputClass={inputClass}
                    onCancel={() => setDeleteOpen(false)}
                    onDeleted={() => setDeleteOpen(false)}
                  />
                )}
              </div>

            </div>
          )}
        </div>
      </div>
    </div>
  );
}
