"use client";
import { useState, useEffect, useRef } from "react";
import { signOut } from "next-auth/react";
import { useI18n, Language } from "@/lib/i18n";
import { useTheme, ThemeMode } from "@/app/providers";
import { LanguageSelector } from "@/components/ui/LanguageSelector";

interface User { id: string; name?: string | null; email?: string | null }
interface List { id: string; name: string; color: string; icon: string; _count?: { tasks: number } }

const LIST_COLORS = ["#4B7BF5", "#EF4444", "#10B981", "#F59E0B", "#8B5CF6", "#EC4899", "#06B6D4", "#F97316", "#6366F1", "#14B8A6"];

interface SidebarProps {
  user: User;
  lists: List[];
  setLists: React.Dispatch<React.SetStateAction<List[]>>;
  selectedListId: string | null;
  onListSelect: (id: string) => void;
  mobileOpen: boolean;
  onClose: () => void;
  isDemo?: boolean;
  onDemoCreateList?: (name: string, color: string) => void;
  onDemoDeleteList?: (id: string) => void;
}

export function Sidebar({
  user,
  lists,
  setLists,
  selectedListId,
  onListSelect,
  mobileOpen,
  onClose,
  isDemo = false,
  onDemoCreateList,
  onDemoDeleteList,
}: SidebarProps) {
  const { t, lang, setLang } = useI18n();
  const { theme, setTheme, toggleTheme } = useTheme();

  const [showNewList, setShowNewList] = useState(false);
  const [newListName, setNewListName] = useState("");
  const [newListColor, setNewListColor] = useState(LIST_COLORS[0]);
  const [userMenuOpen, setUserMenuOpen] = useState(false);
  const [showImport, setShowImport] = useState(false);
  const [importListId, setImportListId] = useState("");
  const [importing, setImporting] = useState(false);
  const [importResult, setImportResult] = useState("");

  const inputRef = useRef<HTMLInputElement>(null);
  const fileRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!isDemo) {
      fetch("/api/lists")
        .then((r) => (r.ok ? r.json() : []))
        .then((data) => {
          if (Array.isArray(data)) {
            setLists(data);
            if (!selectedListId && data.length > 0) onListSelect(data[0].id);
          }
        })
        .catch((err) => console.error("Failed to load lists", err));
    }
  }, [isDemo]);

  useEffect(() => {
    if (showNewList) setTimeout(() => inputRef.current?.focus(), 50);
  }, [showNewList]);

  const createList = async () => {
    const name = newListName.trim();
    if (!name) return;

    if (isDemo) {
      if (onDemoCreateList) onDemoCreateList(name, newListColor);
      setNewListName("");
      setShowNewList(false);
      return;
    }

    try {
      const res = await fetch("/api/lists", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, color: newListColor }),
      });
      if (res.ok) {
        const list = await res.json();
        setLists((prev) => [...prev, list]);
        setNewListName("");
        setShowNewList(false);
        onListSelect(list.id);
      }
    } catch (err) {
      console.error("Failed to create list", err);
    }
  };

  const deleteList = async (id: string) => {
    if (!confirm(t("deleteListConfirm"))) return;

    if (isDemo) {
      if (onDemoDeleteList) onDemoDeleteList(id);
      return;
    }

    try {
      await fetch(`/api/lists/${id}`, { method: "DELETE" });
      setLists((prev) => {
        const updated = prev.filter((l) => l.id !== id);
        if (selectedListId === id) onListSelect(updated[0]?.id || "");
        return updated;
      });
    } catch (err) {
      console.error("Failed to delete list", err);
    }
  };

  const handleImport = async () => {
    const file = fileRef.current?.files?.[0];
    if (!file || !importListId) return;

    if (isDemo) {
      setImportResult("✓ Demo Mode: Import simulated successfully");
      setTimeout(() => { setShowImport(false); setImportResult(""); }, 1500);
      return;
    }

    setImporting(true);
    try {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("listId", importListId);
      const res = await fetch("/api/import", { method: "POST", body: formData });
      const data = await res.json().catch(() => ({}));
      if (res.ok) {
        setImportResult(`✓ Imported ${data.imported} tasks`);
        if (fileRef.current) fileRef.current.value = "";
        const listsRes = await fetch("/api/lists");
        if (listsRes.ok) {
          const updated = await listsRes.json();
          if (Array.isArray(updated)) setLists(updated);
        }
        setTimeout(() => { setShowImport(false); setImportResult(""); }, 2000);
      } else {
        setImportResult(`Error: ${data.error || "Import failed"}`);
      }
    } catch (err) {
      console.error("[Sidebar] import failed", err);
      setImportResult("Error: Network error");
    } finally {
      setImporting(false);
    }
  };

  const initials = user.name?.split(" ").map((n) => n[0]).join("").toUpperCase().slice(0, 2) || "?";

  return (
    <aside className={`sidebar${mobileOpen ? " mobile-open" : ""}`}>
      {/* Header */}
      <div className="sidebar-header">
        <div className="sidebar-logo">✓</div>
        <div style={{ display: "flex", flexDirection: "column" }}>
          <span className="sidebar-title">{t("appName")}</span>
          {isDemo && (
            <span style={{ fontSize: 10, color: "var(--accent)", fontWeight: 700, letterSpacing: 0.3 }}>
              {t("demoBadge")}
            </span>
          )}
        </div>

        {/* Top Quick Actions (Lang & Theme) */}
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 6 }}>
          {/* Custom Language Selector Popover */}
          <LanguageSelector />

          {/* Theme 3-Way Toggle Button */}
          <button
            className="icon-btn"
            id="theme-toggle"
            onClick={toggleTheme}
            title={`${t("theme")}: ${theme === "system" ? t("themeSystem") : theme === "light" ? t("themeLight") : t("themeDark")}`}
            style={{ width: 28, height: 28 }}
          >
            {theme === "system" ? (
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
                <line x1="8" y1="21" x2="16" y2="21" />
                <line x1="12" y1="17" x2="12" y2="21" />
              </svg>
            ) : theme === "light" ? (
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <circle cx="12" cy="12" r="5" /><line x1="12" y1="1" x2="12" y2="3" /><line x1="12" y1="21" x2="12" y2="23" /><line x1="4.22" y1="4.22" x2="5.64" y2="5.64" /><line x1="18.36" y1="18.36" x2="19.78" y2="19.78" /><line x1="1" y1="12" x2="3" y2="12" /><line x1="21" y1="12" x2="23" y2="12" /><line x1="4.22" y1="19.78" x2="5.64" y2="18.36" /><line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
              </svg>
            ) : (
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
              </svg>
            )}
          </button>
        </div>
      </div>

      {/* Nav */}
      <nav className="sidebar-nav">
        <div className="sidebar-section">
          <div className="sidebar-section-label">{t("lists")}</div>
          {lists.map((list) => (
            <div
              key={list.id}
              className={`sidebar-item${selectedListId === list.id ? " active" : ""}`}
              onClick={() => onListSelect(list.id)}
              id={`list-item-${list.id}`}
            >
              <div className="list-dot" style={{ background: list.color }} />
              <span className="item-label">{list.name}</span>
              <span className="item-count">{list._count?.tasks || ""}</span>
              <button
                className="icon-btn"
                style={{ width: 22, height: 22, opacity: 0.5 }}
                onClick={(e) => {
                  e.stopPropagation();
                  deleteList(list.id);
                }}
                title="Delete list"
              >
                <svg width="12" height="12" 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 6" /><path d="M10 11v6M14 11v6" /><path d="M9 6V4h6v2" />
                </svg>
              </button>
            </div>
          ))}
        </div>

        {/* New list */}
        {showNewList ? (
          <div style={{ padding: "4px 8px" }}>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6, padding: "6px 4px 8px" }}>
              {LIST_COLORS.map((c) => (
                <div
                  key={c}
                  className={`color-swatch${newListColor === c ? " selected" : ""}`}
                  style={{ background: c, color: c }}
                  onClick={() => setNewListColor(c)}
                />
              ))}
            </div>
            <input
              ref={inputRef}
              className="form-input"
              placeholder={t("listNamePlaceholder")}
              value={newListName}
              onChange={(e) => setNewListName(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") createList();
                if (e.key === "Escape") setShowNewList(false);
              }}
              style={{ marginBottom: 6 }}
            />
            <div style={{ display: "flex", gap: 6 }}>
              <button className="btn btn-primary btn-sm" style={{ flex: 1 }} onClick={createList}>{t("create")}</button>
              <button className="btn btn-ghost btn-sm" onClick={() => setShowNewList(false)}>{t("cancel")}</button>
            </div>
          </div>
        ) : (
          <button id="new-list-btn" className="sidebar-add-btn" onClick={() => setShowNewList(true)}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
              <line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
            </svg>
            {t("newList")}
          </button>
        )}

        <div className="sidebar-section" style={{ borderTop: "1px solid var(--border)", paddingTop: 12, marginTop: 4 }}>
          <button id="import-btn" className="sidebar-add-btn" onClick={() => { setShowImport(true); setImportListId(lists[0]?.id || ""); }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="17 8 12 3 7 8" /><line x1="12" y1="3" x2="12" y2="15" />
            </svg>
            {t("importTasks")}
          </button>
        </div>
      </nav>

      {/* User footer */}
      <div className="sidebar-footer">
        <div className="user-card" id="user-menu-btn" onClick={() => setUserMenuOpen((p) => !p)} style={{ position: "relative" }}>
          <div className="user-avatar" style={{ background: "#4B7BF5" }}>{initials}</div>
          <div className="user-info">
            <div className="user-name">{user.name || (isDemo ? "Demo User" : "User")}</div>
            <div className="user-email">{user.email || (isDemo ? "demo@checkflow.local" : "")}</div>
          </div>
          {userMenuOpen && (
            <div className="dropdown" style={{ bottom: "100%", left: 0, right: 0, marginBottom: 4 }}>
              {isDemo ? (
                <div
                  className="dropdown-item"
                  onClick={() => { window.location.href = "/login"; }}
                >
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4" /><polyline points="10 17 15 12 10 7" /><line x1="15" y1="12" x2="3" y2="12" />
                  </svg>
                  {t("signIn")}
                </div>
              ) : (
                <div className="dropdown-item danger" id="signout-btn" onClick={() => signOut({ callbackUrl: "/login" })}>
                  <svg width="14" height="14" 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-2h4" /><polyline points="16 17 21 12 16 7" /><line x1="21" y1="12" x2="9" y2="12" />
                  </svg>
                  {t("signOut")}
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Import modal */}
      {showImport && (
        <div className="modal-overlay" onClick={() => setShowImport(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()}>
            <h2 className="modal-title">{t("importModalTitle")}</h2>
            <div className="form-group">
              <label className="form-label">{t("targetList")}</label>
              <select className="form-input" value={importListId} onChange={(e) => setImportListId(e.target.value)}>
                {lists.map((l) => <option key={l.id} value={l.id}>{l.name}</option>)}
              </select>
            </div>
            <div className="form-group">
              <label className="form-label">{t("fileSelectLabel")}</label>
              <input ref={fileRef} type="file" accept=".csv,.ics" className="form-input" />
            </div>
            <p style={{ fontSize: 12, color: "var(--text-tertiary)", marginBottom: 12 }}>
              {t("tickTickExportHint")}
            </p>
            {importResult && (
              <p style={{ fontSize: 13, color: importResult.startsWith("✓") ? "var(--success)" : "var(--danger)", marginBottom: 12 }}>
                {importResult}
              </p>
            )}
            <div className="modal-footer">
              <button className="btn btn-ghost" onClick={() => setShowImport(false)}>{t("cancel")}</button>
              <button id="import-submit-btn" className="btn btn-primary" onClick={handleImport} disabled={importing}>
                {importing ? t("importing") : t("importBtn")}
              </button>
            </div>
          </div>
        </div>
      )}
    </aside>
  );
}