"use client";

import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useAppDispatch } from "@/store/hooks";
import { logout } from "@/store/slices/authSlice";
import { resetStore } from "@/store/resetAction";
import { getStoredUser } from "@/lib/utils/persistAuth";
import { getPremiumStatus, setPremiumStatus } from "@/lib/utils/permissions";
import { clearSession } from "@/lib/utils/clearSession";
import { useToast } from "@/lib/toast";
import { LOCALE_LABELS, SUPPORTED_LOCALES } from "@/lib/constants/locales";
import TransactionListModal from "./TransactionListModal";

interface StaticPage {
  id: number;
  title: string;
  slug: string;
  content?: string;
}

interface SettingsModalProps {
  open: boolean;
  onClose: () => void;
}

const LANG_CODES: Record<string, string> = { en: "EN", gu: "GU", hi: "HI", ar: "AR" };

export default function SettingsModal({ open, onClose }: SettingsModalProps) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { success, error: showError } = useToast();
  const [visible, setVisible] = useState(false);
  const [pages, setPages] = useState<StaticPage[]>([]);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [currentLocale, setCurrentLocale] = useState("en");
  const [txModalOpen, setTxModalOpen] = useState(false);
  const isPremium = getPremiumStatus();
  const user = getStoredUser();
  const fetchedRef = useRef(false);

  // Animate in
  useEffect(() => {
    if (open) {
      requestAnimationFrame(() => setVisible(true));
      document.body.style.overflow = "hidden";
      if (!fetchedRef.current) {
        fetchedRef.current = true;
        fetchPages();
      }
      // Detect current locale from cookie
      const localeCookie = document.cookie.split(";").find(c => c.trim().startsWith("NEXT_LOCALE="));
      if (localeCookie) setCurrentLocale(localeCookie.split("=")[1].trim());
    } else {
      setVisible(false);
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  async function fetchPages() {
    try {
      const { default: apiClient } = await import("@/services/api.client");
      const { API_ENDPOINTS } = await import("@/lib/constants/apiEndpoints");
      const { data } = await apiClient.post<{ result: StaticPage[] }>(
        API_ENDPOINTS.GET_PAGES, {},
      );
      setPages(data.result ?? []);
    } catch {
      setPages([]);
    }
  }

  function switchLocale(loc: string) {
    document.cookie = `NEXT_LOCALE=${loc};path=/;max-age=31536000`;
    setCurrentLocale(loc);
    window.location.reload();
  }

  async function handleLogout() {
    // 1. Redux logout action
    dispatch(logout());
    // 2. Reset entire Redux store to initial state
    dispatch(resetStore());
    // 3. Wipe localStorage + cookies
    clearSession();
    // 4. Navigate to login
    onClose();
    router.push("/login");
    success("Logged out successfully");
  }

  async function handleDeleteAccount() {
    dispatch(logout());
    dispatch(resetStore());
    clearSession();
    setPremiumStatus(false);
    onClose();
    setDeleteDialogOpen(false);
    router.push("/login");
    success("Account deleted successfully");
  }

  if (!open && !visible) return null;

  return (
    <>
      {/* Backdrop */}
      <div
        onClick={onClose}
        style={{
          position: "fixed", inset: 0,
          background: "rgba(14,14,17,0.55)",
          backdropFilter: "blur(3px)",
          zIndex: 1000,
          opacity: visible ? 1 : 0,
          transition: "opacity 0.22s ease",
        }}
      />

      {/* Side drawer */}
      <div
        style={{
          position: "fixed",
          top: 0, right: 0, bottom: 0,
          width: "min(420px, 100vw)",
          background: "var(--surf, #ffffff)",
          zIndex: 1001,
          display: "flex",
          flexDirection: "column",
          transform: visible ? "translateX(0)" : "translateX(100%)",
          transition: "transform 0.32s cubic-bezier(0.32,0.72,0,1)",
          boxShadow: "-8px 0 40px rgba(0,0,0,0.15)",
          overflowY: "auto",
        }}
      >
        {/* ── Header ── */}
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "1.25rem 1.375rem",
          borderBottom: "1px solid var(--border, #e5e7eb)",
          flexShrink: 0,
          position: "sticky", top: 0, background: "var(--surf, #fff)", zIndex: 1,
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: "0.625rem" }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--ink, #0e0e11)" strokeWidth="2">
              <circle cx="12" cy="12" r="3" />
              <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
            </svg>
            <h2 style={{ margin: 0, fontSize: "1rem", fontWeight: 800, color: "var(--ink, #0e0e11)" }}>Settings</h2>
          </div>
          <button onClick={onClose} style={{ width: 32, height: 32, borderRadius: "50%", background: "var(--bg, #f8f9fb)", border: "1px solid var(--border, #e5e7eb)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", fontSize: 16, color: "var(--text-2, #6b7280)" }}>✕</button>
        </div>

        <div style={{ flex: 1, padding: "0 1.375rem 2rem" }}>

          {/* ── User info ── */}
          {user && (
            <div style={{ padding: "1.125rem 0", borderBottom: "1px solid var(--border, #e5e7eb)", display: "flex", alignItems: "center", gap: "0.875rem" }}>
              <div style={{ width: 44, height: 44, borderRadius: "50%", background: "var(--brand, #C1272D)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <span style={{ color: "#fff", fontWeight: 800, fontSize: 16 }}>
                  {user.full_name?.charAt(0)?.toUpperCase() ?? "?"}
                </span>
              </div>
              <div>
                <p style={{ margin: 0, fontWeight: 700, fontSize: "0.9375rem", color: "var(--ink, #0e0e11)" }}>{user.full_name}</p>
                <p style={{ margin: 0, fontSize: "0.75rem", color: "var(--text-2, #6b7280)", fontFamily: "var(--mono, monospace)" }}>{user.email}</p>
              </div>
            </div>
          )}

          {/* ── Subscription ── */}
          <Section label="Subscription">
            {isPremium ? (
              <div style={{ padding: "0.875rem", background: "linear-gradient(135deg, rgba(193,39,45,0.08) 0%, rgba(193,39,45,0.04) 100%)", border: "1.5px solid rgba(193,39,45,0.2)", borderRadius: 10 }}>
                <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", marginBottom: "0.25rem" }}>
                  <span style={{ fontSize: 14 }}>⭐</span>
                  <span style={{ fontWeight: 700, color: "var(--brand, #C1272D)", fontSize: "0.875rem" }}>DTNews Premium</span>
                </div>
                <p style={{ margin: 0, fontSize: "0.75rem", color: "var(--text-2, #6b7280)" }}>All premium features unlocked</p>
              </div>
            ) : (
              <div style={{ padding: "0.875rem", background: "var(--bg, #f8f9fb)", border: "1px solid var(--border, #e5e7eb)", borderRadius: 10 }}>
                <p style={{ margin: "0 0 0.5rem", fontWeight: 600, fontSize: "0.875rem", color: "var(--ink, #0e0e11)" }}>Free plan</p>
                <p style={{ margin: "0 0 0.875rem", fontSize: "0.75rem", color: "var(--text-2, #6b7280)" }}>Upgrade to unlock e-paper, premium articles, and more</p>
                <Link href="/subscribe" onClick={onClose} style={{ display: "inline-flex", alignItems: "center", gap: "0.375rem", padding: "0.4375rem 1rem", background: "var(--brand, #C1272D)", color: "#fff", borderRadius: 7, fontWeight: 700, fontSize: "0.8125rem", textDecoration: "none" }}>
                  Upgrade to Premium
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12h14M13 6l6 6-6 6" /></svg>
                </Link>
              </div>
            )}
            <button
              onClick={() => setTxModalOpen(true)}
              style={{
                display: "flex", alignItems: "center", gap: "0.75rem",
                padding: "0.6875rem 0.75rem",
                borderRadius: 8,
                background: "none",
                border: "none",
                cursor: "pointer",
                width: "100%",
                textAlign: "left",
                fontSize: "0.875rem",
                fontWeight: 500,
                color: "var(--ink, #0e0e11)",
                transition: "background 0.12s",
              }}
              onMouseEnter={(e) => (e.currentTarget.style.background = "var(--bg, #f8f9fb)")}
              onMouseLeave={(e) => (e.currentTarget.style.background = "none")}
            >
              <span style={{ width: 28, height: 28, borderRadius: 7, background: "var(--bg, #f8f9fb)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, color: "var(--text-2, #6b7280)" }}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <rect x="2" y="5" width="20" height="14" rx="2" />
                  <path d="M2 10h20" />
                </svg>
              </span>
              <span>Transaction History</span>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ marginLeft: "auto", color: "var(--text-3, #9ca3af)" }}>
                <path d="M9 18l6-6-6-6" />
              </svg>
            </button>
          </Section>

          {/* ── Language ── */}
          <Section label="Language">
            <div style={{ display: "flex", flexWrap: "wrap", gap: "0.5rem" }}>
              {SUPPORTED_LOCALES.map((loc) => (
                <button
                  key={loc}
                  onClick={() => switchLocale(loc)}
                  style={{
                    padding: "0.4375rem 0.875rem",
                    borderRadius: 99,
                    border: `1.5px solid ${currentLocale === loc ? "var(--brand, #C1272D)" : "var(--border, #e5e7eb)"}`,
                    background: currentLocale === loc ? "var(--brand, #C1272D)" : "transparent",
                    color: currentLocale === loc ? "#fff" : "var(--ink, #0e0e11)",
                    fontWeight: currentLocale === loc ? 700 : 500,
                    fontSize: "0.8125rem",
                    cursor: "pointer",
                    transition: "all 0.15s",
                    display: "flex", alignItems: "center", gap: "0.375rem",
                  }}
                >
                  <span style={{ fontFamily: "var(--mono, monospace)", fontSize: 10, letterSpacing: "0.06em" }}>{LANG_CODES[loc] ?? loc.toUpperCase()}</span>
                  {LOCALE_LABELS[loc]}
                </button>
              ))}
            </div>
          </Section>

          {/* ── Pages from API ── */}
          {pages.length > 0 && (
            <Section label="Information">
              {pages.map((page, idx) => (
                <SettingRow
                  key={`page-${page.id ?? idx}-${idx}`}
                  icon={
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                      <polyline points="14 2 14 8 20 8" />
                    </svg>
                  }
                  label={page.title}
                  href={`/company/${page.slug}`}
                  onClick={onClose}
                />
              ))}
            </Section>
          )}

          {/* ── App ── */}
          <Section label="App">
            <SettingRow
              icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10" /><path d="M12 8v4M12 16h.01" /></svg>}
              label="About DTNews"
              href="/company/about"
              onClick={onClose}
            />
            <SettingRow
              icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.69 13.6 19.79 19.79 0 0 1 1.61 5a2 2 0 0 1 1.99-2H6.6a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L7.91 10.1a16 16 0 0 0 6 6l.97-.97a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 17.42z" /></svg>}
              label="Contact Support"
              href="/company/contact"
              onClick={onClose}
            />
          </Section>

          {/* ── Danger zone ── */}
          <Section label="Account">
            <button
              onClick={handleLogout}
              style={dangerRowStyle(false)}
            >
              <span style={iconWrap("#6b7280")}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9" />
                </svg>
              </span>
              <span>Log out</span>
            </button>

            <button
              onClick={() => setDeleteDialogOpen(true)}
              style={dangerRowStyle(true)}
            >
              <span style={iconWrap("#C1272D")}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <polyline points="3 6 5 6 21 6" />
                  <path d="M19 6l-1 14H6L5 6M10 11v6M14 11v6M9 6V4h6v2" />
                </svg>
              </span>
              <span style={{ color: "#C1272D", fontWeight: 600 }}>Delete account</span>
            </button>
          </Section>

          <p style={{ fontSize: 11, color: "var(--text-3, #9ca3af)", textAlign: "center", fontFamily: "var(--mono, monospace)", marginTop: "1.5rem" }}>
            DTNews · DivineTechs IT Company · v1.5
          </p>
        </div>
      </div>
      {/* ── Transaction list modal ── */}
      <TransactionListModal
        open={txModalOpen}
        onClose={() => setTxModalOpen(false)}
      />

      {/* ── Delete account confirmation modal ── */}
      {deleteDialogOpen && (
        <>
          <div
            onClick={() => setDeleteDialogOpen(false)}
            style={{ position: "fixed", inset: 0, background: "rgba(14,14,17,0.65)", backdropFilter: "blur(4px)", zIndex: 1100 }}
          />
          <div style={{
            position: "fixed",
            top: "50%", left: "50%",
            transform: "translate(-50%, -50%)",
            width: "min(420px, calc(100vw - 2rem))",
            background: "#fff",
            borderRadius: 16,
            padding: "2rem 1.75rem",
            zIndex: 1101,
            boxShadow: "0 24px 64px rgba(0,0,0,0.22)",
            textAlign: "center",
          }}>
            {/* Warning icon */}
            <div style={{
              width: 56, height: 56, borderRadius: "50%",
              background: "rgba(193,39,45,0.08)",
              border: "2px solid rgba(193,39,45,0.2)",
              display: "flex", alignItems: "center", justifyContent: "center",
              margin: "0 auto 1.125rem",
            }}>
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#C1272D" strokeWidth="2" strokeLinecap="round">
                <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
                <line x1="12" y1="9" x2="12" y2="13" />
                <line x1="12" y1="17" x2="12.01" y2="17" />
              </svg>
            </div>

            <h3 style={{ margin: "0 0 0.5rem", fontSize: "1.0625rem", fontWeight: 800, color: "#0e0e11" }}>
              Delete your account?
            </h3>
            <p style={{ margin: "0 0 1.5rem", fontSize: "0.875rem", color: "#6b7280", lineHeight: 1.55 }}>
              This will permanently delete your account and all your data.
              <strong style={{ display: "block", color: "#0e0e11", marginTop: "0.25rem" }}>This action cannot be undone.</strong>
            </p>

            <div style={{ display: "flex", gap: "0.75rem" }}>
              <button
                onClick={() => setDeleteDialogOpen(false)}
                style={{ flex: 1, padding: "0.6875rem", background: "none", border: "1.5px solid #e5e7eb", borderRadius: 9, fontWeight: 600, fontSize: "0.9rem", cursor: "pointer", color: "#0e0e11" }}
              >
                Cancel
              </button>
              <button
                onClick={handleDeleteAccount}
                style={{ flex: 1, padding: "0.6875rem", background: "#C1272D", border: "none", borderRadius: 9, fontWeight: 700, fontSize: "0.9rem", cursor: "pointer", color: "#fff" }}
              >
                Yes, delete
              </button>
            </div>
          </div>
        </>
      )}
    </>
  );
}

// ── Sub-components ────────────────────────────────────────────────────────────
function Section({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div style={{ paddingTop: "1.375rem" }}>
      <p style={{ margin: "0 0 0.625rem", fontSize: 10, fontWeight: 800, letterSpacing: "0.1em", textTransform: "uppercase" as const, color: "var(--text-3, #9ca3af)", fontFamily: "var(--mono, monospace)" }}>
        {label}
      </p>
      <div style={{ display: "flex", flexDirection: "column", gap: "0.25rem" }}>
        {children}
      </div>
    </div>
  );
}

function SettingRow({ icon, label, href, onClick }: { icon: React.ReactNode; label: string; href: string; onClick?: () => void }) {
  return (
    <a
      href={href}
      onClick={onClick}
      style={{ display: "flex", alignItems: "center", gap: "0.75rem", padding: "0.6875rem 0.75rem", borderRadius: 8, background: "none", border: "none", cursor: "pointer", textDecoration: "none", color: "var(--ink, #0e0e11)", fontSize: "0.875rem", fontWeight: 500, transition: "background 0.12s" }}
      onMouseEnter={(e) => (e.currentTarget.style.background = "var(--bg, #f8f9fb)")}
      onMouseLeave={(e) => (e.currentTarget.style.background = "none")}
    >
      <span style={{ color: "var(--text-2, #6b7280)", display: "flex" }}>{icon}</span>
      {label}
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ marginLeft: "auto", color: "var(--text-3, #9ca3af)" }}>
        <path d="M9 18l6-6-6-6" />
      </svg>
    </a>
  );
}

function dangerRowStyle(isDanger: boolean): React.CSSProperties {
  return {
    display: "flex",
    alignItems: "center",
    gap: "0.75rem",
    padding: "0.6875rem 0.75rem",
    borderRadius: 8,
    background: "none",
    border: "none",
    cursor: "pointer",
    width: "100%",
    textAlign: "left",
    fontSize: "0.875rem",
    fontWeight: 500,
    color: isDanger ? "#C1272D" : "var(--ink, #0e0e11)",
    transition: "background 0.12s",
  };
}

function iconWrap(color: string): React.CSSProperties {
  return {
    width: 28, height: 28,
    borderRadius: 7,
    background: color === "#C1272D" ? "rgba(193,39,45,0.08)" : "var(--bg, #f8f9fb)",
    display: "flex", alignItems: "center", justifyContent: "center",
    flexShrink: 0,
    color,
  };
}
