import React, { useEffect, useMemo, useState } from "react";
import { Axiosinstance } from "../services/auth/Axiosinstance";
import { useToast } from "../components/ToastProvider";

import PageHeader from "../components/ui/PageHeader";
import Button from "../components/ui/Button";
import SkeletonList from "../components/ui/SkeletonList";

import { LuRefreshCcw } from "react-icons/lu";
import { FiRefreshCw } from "react-icons/fi";

import useCooldownAction from "../hooks/useCooldownAction";
import { getErrMsg } from "../utils/account";

import FtpAccountCard from "../components/ftp/FtpAccountCard";
import FtpEmptyStateCard from "../components/ftp/FtpEmptyStateCard";
import FtpServerNotConfiguredCard from "../components/ftp/FtpServerNotConfiguredCard";

const normalizeHostFromBaseUrl = (raw = "") =>
  String(raw).replace(/^https?:\/\//, "").replace(/\/$/, "");

export default function Ftp() {
  const { success, error: toastError, info } = useToast();

  const [loading, setLoading] = useState(true);
  const [provisioning, setProvisioning] = useState(false);
  const [resettingPass, setResettingPass] = useState(false);

  const [account, setAccount] = useState(null);

  // فقط provision/reset ست میشه
  const [secret, setSecret] = useState(null); // { password, host, port } | null
  const [showPassword, setShowPassword] = useState(false);

  const [notProvisioned, setNotProvisioned] = useState(false);
  const [serverNotConfigured, setServerNotConfigured] = useState(false);
  const [error, setError] = useState("");

  // Sync states
  const [syncing, setSyncing] = useState(false);
  const [syncCooldownLeft, setSyncCooldownLeft] = useState(0); // ms

  const resetFlags = () => {
    setAccount(null);
    setSecret(null);
    setShowPassword(false);
    setNotProvisioned(false);
    setServerNotConfigured(false);
  };

  const parseAndSetKnownErrors = (e, { toast = true } = {}) => {
    const status = e?.response?.status;
    const detail = e?.response?.data?.detail || "";

    setNotProvisioned(false);
    setServerNotConfigured(false);

    if (status === 404 && detail === "No FTP account provisioned.") {
      setNotProvisioned(true);
      setAccount(null);
      setSecret(null);
      setShowPassword(false);
      setError("");
      if (toast) info("اکانت SFTP هنوز ساخته نشده. دکمه «ساخت اکانت» را بزن.", { title: "FTP/SFTP" });
      return true;
    }

    if (status === 400 && detail === "No active SFTPGo server configured.") {
      setServerNotConfigured(true);
      setAccount(null);
      setSecret(null);
      setShowPassword(false);
      setError("");
      if (toast) toastError("سرور فعال برای SFTPGo تنظیم نشده است.", { title: "FTP/SFTP" });
      return true;
    }

    return false;
  };

  // GET account
  const fetchMe = async (showToast = true) => {
    setLoading(true);
    setError("");
    resetFlags();

    try {
      const res = await Axiosinstance.get("ftp/me/");
      setAccount(res.data);
      setSecret(null);
      setShowPassword(false);
      if (showToast) success("اطلاعات اکانت بروزرسانی شد.", { title: "FTP/SFTP" });
    } catch (e) {
      const handled = parseAndSetKnownErrors(e, { toast: showToast });
      if (!handled) {
        const msg = getErrMsg(e, "خطا در دریافت اطلاعات اکانت");
        setError(msg);
        if (showToast) toastError(msg, { title: "خطا" });
      }
    } finally {
      setLoading(false);
    }
  };

  // Refresh guard
  const refresh = useCooldownAction({
    cooldownMs: 3000,
    toastGapMs: 900,
    isBusy: loading || syncing || provisioning || resettingPass,
    busyMessage: "در حال انجام عملیات...",
    busyToast: info,
    title: "FTP/SFTP",
    onRun: async () => {
      await fetchMe(true);
    },
  });

  // ✅ POST /ftp/me/ => { account, password, sftp_host, sftp_port }
  const provision = async () => {
    if (provisioning || loading) return;

    setProvisioning(true);
    setError("");
    resetFlags();

    try {
      const res = await Axiosinstance.post("ftp/me/");
      const data = res.data || {};
      const acc = data.account || null;

      setAccount(acc);

      const hostFallback = normalizeHostFromBaseUrl(acc?.server?.base_url || "");
      setSecret({
        password: data.password || "",
        host: data.sftp_host || hostFallback,
        port: String(data.sftp_port || 2022),
      });

      setShowPassword(false);

      success("اکانت SFTP ساخته شد ✅", { title: "FTP/SFTP" });
      info("پسورد فقط یک‌بار نمایش داده می‌شود؛ بهتر است همین الان کپی کنی.", { title: "نکته" });
    } catch (e) {
      const handled = parseAndSetKnownErrors(e, { toast: true });
      if (!handled) {
        const msg = getErrMsg(e, "خطا در ساخت اکانت");
        setError(msg);
        toastError(msg, { title: "خطا" });
      }
    } finally {
      setProvisioning(false);
    }
  };

  // ✅ POST /ftp/me/reset-password/
  const resetPassword = async () => {
    if (!account) {
      info("اول باید اکانت ساخته شده باشد.", { title: "FTP/SFTP" });
      return;
    }
    if (resettingPass || loading) return;

    setResettingPass(true);
    setError("");

    try {
      const res = await Axiosinstance.post("ftp/me/reset-password/");
      const data = res.data || {};

      const acc =
        data.account ||
        (data.id
          ? {
              id: data.id,
              username: data.username,
              home_dir: data.home_dir,
              is_active: data.is_active,
              server: data.server,
              created_at: data.created_at,
              updated_at: data.updated_at,
            }
          : account);

      setAccount(acc);

      const hostFromServer = normalizeHostFromBaseUrl(acc?.server?.base_url || "");
      setSecret({
        password: data.password || "",
        host: data.sftp_host || hostFromServer,
        port: String(data.sftp_port || 2022),
      });

      setShowPassword(false);

      success("پسورد جدید ساخته شد ✅", { title: "FTP/SFTP" });
      info("پسورد را همین الان کپی کن.", { title: "نکته" });
    } catch (e) {
      const handled = parseAndSetKnownErrors(e, { toast: true });
      if (!handled) {
        const msg = getErrMsg(e, "خطا در ریست پسورد");
        setError(msg);
        toastError(msg, { title: "خطا" });
      }
    } finally {
      setResettingPass(false);
    }
  };

  // ✅ Sync NOW + 3s cooldown
  const syncNow = async () => {
    // اگر اکانت نداریم یا هنوز ساخته نشده، سینک معنی نداره
    if (!account || notProvisioned || serverNotConfigured) {
      info("اول باید اکانت SFTP ساخته شده باشد.", { title: "FTP/SFTP" });
      return;
    }

    if (syncing || loading || syncCooldownLeft > 0) return;

    try {
      setSyncing(true);
      setError("");

      await Axiosinstance.post("storage/sftp/sync-now/");

      success("همگام‌سازی فایل‌های FTP شروع شد ✅", { title: "FTP/SFTP" });

      // بعد از انجام همگام‌سازی: 3 ثانیه قفل
      setSyncCooldownLeft(3000);
    } catch (e) {
      const handled = parseAndSetKnownErrors(e, { toast: true });
      if (!handled) {
        const msg = getErrMsg(e, "خطا در همگام‌سازی FTP");
        setError(msg);
        toastError(msg, { title: "خطا" });
      }
      setSyncCooldownLeft(3000);
    } finally {
      setSyncing(false);
    }
  };

  // Countdown cooldown (هر ۱ ثانیه)
  useEffect(() => {
    if (syncCooldownLeft <= 0) return;

    const t = setInterval(() => {
      setSyncCooldownLeft((ms) => Math.max(0, ms - 1000));
    }, 1000);

    return () => clearInterval(t);
  }, [syncCooldownLeft]);

  useEffect(() => {
    fetchMe(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const connectionInfo = useMemo(() => {
    if (!account) return null;

    const host = normalizeHostFromBaseUrl(account?.server?.base_url || "");
    return {
      host: secret?.host || host || "-",
      port: secret?.port || "2022",
      username: account.username || "-",
      homeDir: account.home_dir || "-",
      serverName: account?.server?.name || "-",
      serverUrl: account?.server?.base_url || "-",
      password: secret?.password || "",
    };
  }, [account, secret]);

  const copy = async (text, label = "متن") => {
    if (!text || text === "-") {
      toastError("چیزی برای کپی وجود ندارد.", { title: "کپی" });
      return false;
    }

    try {
      if (navigator?.clipboard?.writeText) {
        await navigator.clipboard.writeText(text);
        success(`${label} کپی شد ✅`, { title: "کپی" });
        return true;
      }
    } catch {}

    try {
      const ta = document.createElement("textarea");
      ta.value = text;
      ta.style.position = "fixed";
      ta.style.left = "-9999px";
      document.body.appendChild(ta);
      ta.focus();
      ta.select();
      const ok = document.execCommand("copy");
      document.body.removeChild(ta);

      ok
        ? success(`${label} کپی شد ✅`, { title: "کپی" })
        : toastError("کپی انجام نشد. دستی کپی کن.", { title: "کپی" });
      return ok;
    } catch {
      toastError("کپی انجام نشد. اجازه Clipboard را بررسی کن.", { title: "کپی" });
      return false;
    }
  };

  const refreshLabel = loading ? "درحال بروزرسانی..." : "بروزرسانی";
  const refreshTitle = refresh.leftMs > 0 ? `تا ${Math.ceil(refresh.leftMs / 1000)} ثانیه دیگر` : "بروزرسانی اطلاعات";

  const syncDisabled =
    syncing || loading || syncCooldownLeft > 0 || provisioning || resettingPass || notProvisioned || serverNotConfigured;

  const syncLabel =
    syncing ? "درحال همگام‌سازی..." : syncCooldownLeft > 0 ? "همگام‌سازی" : "همگام‌سازی FTP";

  const syncTitle =
    syncCooldownLeft > 0 ? `تا ${Math.ceil(syncCooldownLeft / 1000)} ثانیه دیگر` : "همگام‌سازی فایل‌های آپلود شده از طریق FTP";

  return (
    <div className="dark:text-white w-full space-y-6">
      <PageHeader
        title="FTP / SFTP"
        subtitle="اطلاعات اتصال و مدیریت پسورد"
        right={
          <div className="flex items-center gap-2">
            <Button
              type="button"
              onClick={syncNow}
              disabled={syncDisabled}
              variant="outline"
              size="lg"
              title={syncTitle}
              leftIcon={<FiRefreshCw className={`w-4 h-4 text-[#43BEFF] dark:text-white ${syncing ? "animate-spin" : ""}`} />}
            >
              {syncLabel}
            </Button>

            <Button
              type="button"
              onClick={refresh.run}
              disabled={refresh.disabled || syncing || provisioning || resettingPass}
              variant="outline"
              size="lg"
              title={refreshTitle}
              leftIcon={<LuRefreshCcw className={`w-4 h-4 text-[#43BEFF] dark:text-white ${loading ? "animate-spin" : ""}`} />}
            >
              {refreshLabel}
            </Button>
          </div>
        }
      />

      {loading && (
        <div className="rounded-2xl border border-white/10 bg-white/5 p-5">
          <div className="animate-pulse h-5 w-40 bg-white/10 shadow rounded mb-3" />
          <SkeletonList rows={3} className="!mt-0" />
        </div>
      )}

      {!loading && error && (
        <div className="p-4 shadow rounded-xl border border-red-500/30 bg-red-500/10 text-sm">{error}</div>
      )}

      {!loading && serverNotConfigured && (
        <FtpServerNotConfiguredCard
          onHelp={() => info("ادمین باید یک SFTPGo server فعال تنظیم کند.", { title: "راهنما" })}
        />
      )}

      {/* ✅ اینجا مشکل تو حل شد: onProvision دیگه خالی نیست */}
      {!loading && notProvisioned && !serverNotConfigured && (
        <FtpEmptyStateCard provisioning={provisioning} onProvision={provision} />
      )}

      {!loading && account && connectionInfo && (
        <FtpAccountCard
          account={account}
          connectionInfo={connectionInfo}
          showPassword={showPassword}
          onToggleShowPassword={() => setShowPassword((p) => !p)}
          resettingPass={resettingPass}
          onResetPassword={resetPassword}
          onCopy={copy}
          onWhyInactive={() =>
            info("اکانت شما Inactive است. برای فعال‌سازی/ریست پسورد با ادمین تماس بگیر.", { title: "FTP/SFTP" })
          }
        />
      )}
    </div>
  );
}
