"use client";

import { useState, useEffect } from "react";
import { useLanguage } from "@/components/language-provider";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";

const TRUST_STATE_COLORS: Record<string, string> = {
  basic: "bg-slate-500/20 text-slate-400",
  verified: "bg-amber-500/20 text-amber-400",
  strong: "bg-emerald-500/20 text-emerald-400",
};

const TRUST_STATE_LABELS: Record<string, { fa: string; en: string }> = {
  basic: { fa: "پایه", en: "Basic" },
  verified: { fa: "تأیید شده", en: "Verified" },
  strong: { fa: "قوی", en: "Strong" },
};

export default function SecurityPage() {
  const { lang, dir } = useLanguage();
  const t = (fa: string, en: string) => (lang === "fa" ? fa : en);

  const [mfaEnabled, setMfaEnabled] = useState(false);
  const [setupData, setSetupData] = useState<{ secret: string; qr_code: string; totp_uri: string } | null>(null);
  const [verifyCode, setVerifyCode] = useState("");
  const [currentPassword, setCurrentPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const [trustState, setTrustState] = useState<string | null>(null);
  const [trustScore, setTrustScore] = useState<number | null>(null);
  const [evidenceList, setEvidenceList] = useState<any[]>([]);

  const getToken = () => localStorage.getItem("access_token");

  useEffect(() => {
    fetchMfaStatus();
    fetchTrustState();
  }, []);

  const fetchTrustState = async () => {
    const token = getToken();
    if (!token) return;
    try {
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/verification/trust/me/`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const data = await res.json();
        setTrustState(data.trust_state);
        setTrustScore(data.trust_score);
        setEvidenceList(data.evidence || []);
      }
    } catch (e) {
      console.error(e);
    }
  };

  const fetchMfaStatus = async () => {
    const token = getToken();
    if (!token) return;
    try {
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/mfa/setup/`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.status === 200) {
        const data = await res.json();
        setMfaEnabled(false);
        setSetupData(null);
      } else if (res.status === 400) {
        const data = await res.json();
        if (data.detail && data.detail.includes("already enabled")) {
          setMfaEnabled(true);
        }
      }
    } catch (e) {
      console.error(e);
    }
  };

  const startSetup = async () => {
    setLoading(true);
    setError(null);
    setSuccess(null);
    try {
      const token = getToken();
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/mfa/setup/`, {
        method: "GET",
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const data = await res.json();
        setSetupData(data);
      } else {
        const data = await res.json();
        setError(data.detail || t("خطا در راه‌اندازی MFA", "Error setting up MFA"));
      }
    } catch (e) {
      setError(t("خطا در ارتباط با سرور", "Server connection error"));
    } finally {
      setLoading(false);
    }
  };

  const verifyMfa = async () => {
    setLoading(true);
    setError(null);
    setSuccess(null);
    try {
      const token = getToken();
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/mfa/verify/`, {
        method: "POST",
        headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
        body: JSON.stringify({ code: verifyCode }),
      });
      if (res.ok) {
        setSuccess(t("MFA با موفقیت فعال شد", "MFA enabled successfully"));
        setMfaEnabled(true);
        setSetupData(null);
        setVerifyCode("");
      } else {
        const data = await res.json();
        setError(data.detail || t("کد نامعتبر است", "Invalid code"));
      }
    } catch (e) {
      setError(t("خطا در ارتباط با سرور", "Server connection error"));
    } finally {
      setLoading(false);
    }
  };

  const disableMfa = async () => {
    setLoading(true);
    setError(null);
    setSuccess(null);
    try {
      const token = getToken();
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/mfa/disable/`, {
        method: "POST",
        headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
        body: JSON.stringify({ current_password: currentPassword }),
      });
      if (res.ok) {
        setSuccess(t("MFA با موفقیت غیرفعال شد", "MFA disabled successfully"));
        setMfaEnabled(false);
        setCurrentPassword("");
      } else {
        const data = await res.json();
        setError(data.detail || t("خطا در غیرفعال‌سازی MFA", "Error disabling MFA"));
      }
    } catch (e) {
      setError(t("خطا در ارتباط با سرور", "Server connection error"));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">{t("امنیت", "Security")}</h1>
        <p className="text-slate-400">{t("تنظیمات احراز هویت دو مرحله‌ای (MFA)", "Multi-factor authentication settings")}</p>
      </div>

      {error && (
        <div className="rounded-lg bg-rose-500/15 p-3 text-sm text-rose-400">{error}</div>
      )}
      {success && (
        <div className="rounded-lg bg-emerald-500/15 p-3 text-sm text-emerald-400">{success}</div>
      )}

      <Card>
        <CardHeader>
          <CardTitle>{t("حالت اعتماد", "Trust State")}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center gap-4">
            <div
              className={`rounded-lg px-4 py-2 text-xl font-bold ${
                trustState ? TRUST_STATE_COLORS[trustState] || TRUST_STATE_COLORS.basic : "bg-slate-500/10"
              }`}
            >
              {trustState
                ? TRUST_STATE_LABELS[trustState]?.[lang] || trustState
                : t("در حال بارگذاری...", "Loading...")}
            </div>
            {trustScore !== null && (
              <div className="text-2xl font-bold text-white">{trustScore}/100</div>
            )}
          </div>

          <div className="text-sm text-slate-400">
            {t("تعداد شواهد ثبت‌شده:", "Evidence records:")} {evidenceList.length}
          </div>

          {evidenceList.length > 0 && (
            <div className="space-y-2">
              {evidenceList.map((e) => (
                <div
                  key={e.id}
                  className="flex items-center justify-between rounded-lg border border-white/10 p-2"
                >
                  <span className="text-sm text-slate-300">
                    {e.evidence_type} — {e.dimension}
                  </span>
                  <span className={`text-xs ${TRUST_STATE_COLORS.basic}`}>
                    {e.provider}
                  </span>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>
            {t("احراز هویت دو مرحله‌ای (MFA)", "Multi-Factor Authentication (MFA)")}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="font-medium text-white">
                {t("وضعیت MFA", "MFA Status")}
              </p>
              <p className="text-sm text-slate-400">
                {mfaEnabled
                  ? t("فعال شده", "Enabled")
                  : t("غیرفعال", "Disabled")}
              </p>
            </div>
            {!mfaEnabled && !setupData && (
              <Button onClick={startSetup} disabled={loading}>
                {loading ? t("در حال بارگذاری...", "Loading...") : t("فعال‌سازی MFA", "Enable MFA")}
              </Button>
            )}
          </div>

          {setupData && (
            <div className="space-y-4 rounded-lg border border-white/10 p-4">
              <p className="text-sm text-slate-300">
                {t("کد QR را با برنامه Authenticator خود اسکن کنید:", "Scan this QR code with your authenticator app:")}
              </p>
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={setupData.qr_code}
                alt="MFA QR Code"
                className="h-48 w-48"
              />
              <div>
                <p className="text-sm text-slate-400">{t("کد دستی:", "Manual code:")}</p>
                <code className="block break-all rounded bg-black/30 p-2 text-xs text-slate-300">
                  {setupData.secret}
                </code>
              </div>
              <div>
                <Input
                  type="text"
                  placeholder={t("کد تأیید را وارد کنید", "Enter verification code")}
                  value={verifyCode}
                  onChange={(e) => setVerifyCode(e.target.value)}
                  dir="ltr"
                />
              </div>
              <Button onClick={verifyMfa} disabled={loading || !verifyCode}>
                {loading ? t("در حال تأیید...", "Verifying...") : t("تأیید و فعال‌سازی", "Verify & Enable")}
              </Button>
            </div>
          )}

          {mfaEnabled && (
            <div className="space-y-4 rounded-lg border border-white/10 p-4">
              <p className="text-sm text-slate-300">
                {t("برای غیرفعال‌سازی MFA، رمز عبور فعلی خود را وارد کنید:", "To disable MFA, enter your current password:")}
              </p>
              <div>
                <Input
                  type="password"
                  placeholder={t("رمز عبور فعلی", "Current password")}
                  value={currentPassword}
                  onChange={(e) => setCurrentPassword(e.target.value)}
                  dir="ltr"
                />
              </div>
              <Button variant="secondary" onClick={disableMfa} disabled={loading || !currentPassword}>
                {loading ? t("در حال غیرفعال‌سازی...", "Disabling...") : t("غیرفعال‌سازی MFA", "Disable MFA")}
              </Button>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
