"use client";
import React, { useState, useEffect, useRef } from "react";
import { signOut } from "next-auth/react";
import { useI18n } from "@/lib/i18n";
import { useTheme } from "@/app/providers";
import { LanguageSelector } from "@/components/ui/LanguageSelector";
import { ContextMenu, MenuItem } from "@/components/ui/ContextMenu";
import { SettingsModal } from "@/components/settings/SettingsModal";
import { getCustomTags, MockTag, getAllTrashTasks, getDemoStore } from "@/lib/mockData";

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;
  selectedTag: string | null;
  onTagSelect: (tag: string | null) => void;
  isTrashActive: boolean;
  onTrashSelect: () => 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,
  selectedTag,
  onTagSelect,
  isTrashActive,
  onTrashSelect,
  mobileOpen,
  onClose,
  isDemo = false,
  onDemoCreateList,
  onDemoDeleteList,
}: SidebarProps) {
  const { t } = useI18n();
  const { theme, 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 [showSettings, setShowSettings] = useState(false);
  const [importListId, setImportListId] = useState("");
  const [importing, setImporting] = useState(false);
  const [importResult, setImportResult] = useState("");
  const [tags, setTags] = useState<MockTag[]>([]);
  const [trashCount, setTrashCount] = useState(0);

  // Context Menu for Lists
  const [contextMenu, setContextMenu] = useState<{ x: number; y: number; listId: string } | null>(null);

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

  useEffect(() => {
    setTags(getCustomTags());
    const store = getDemoStore();
    const trashed = getAllTrashTasks(store.tasks);
    setTrashCount(trashed.length);
  }, [lists]);

  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) || "?";

  // List context menu items
  const getListContextMenuItems = (listId: string): MenuItem[] => [
    {
      label: t("deleteListConfirm").split("?")[0],
      icon: "🗑️",
      danger: true,
      onClick: () => deleteList(listId),
    },
  ];

  return (
    <aside className={`sidebar${mobileOpen ? " mobile-open" : ""}`}>
      {/* Header with Logo & Controls */}
      <div className="sidebar-header" style={{ padding: "14px 14px 10px", gap: 8 }}>
        <div className="sidebar-logo">✓</div>
        <div style={{ display: "flex", flexDirection: "column", minWidth: 0, flex: 1 }}>
          <span className="sidebar-title" style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
            {t("appName")}
          </span>
          {isDemo && (
            <span style={{ fontSize: 10, color: "var(--accent)", fontWeight: 700, letterSpacing: 0.3 }}>
              {t("demoBadge")}
            </span>
          )}
        </div>

        {/* Top Controls: Search, Language & Theme */}
        <div style={{ display: "flex", alignItems: "center", gap: 4, flexShrink: 0 }}>
          {/* Quick Search Button */}
          <button
            className="icon-btn"
            id="quick-search-btn"
            onClick={() => document.dispatchEvent(new CustomEvent("checkflow:openCommandPalette"))}
            title="Search (Ctrl+K)"
            style={{ width: 28, height: 28, flexShrink: 0 }}
            type="button"
          >
            🔍
          </button>

          <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, flexShrink: 0 }}
            type="button"
          >
            {theme === "system" ? (
              <svg width="14" height="14" 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="14" height="14" 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="14" height="14" 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 List */}
      <nav className="sidebar-nav">
        {/* Lists Section */}
        <div className="sidebar-section">
          <div className="sidebar-section-label">{t("lists")}</div>
          {lists.map((list) => (
            <div
              key={list.id}
              className={`sidebar-item${!isTrashActive && !selectedTag && selectedListId === list.id ? " active" : ""}`}
              onClick={() => {
                onTagSelect(null);
                onListSelect(list.id);
              }}
              onContextMenu={(e) => {
                e.preventDefault();
                setContextMenu({ x: e.clientX, y: e.clientY, listId: 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.4 }}
                onClick={(e) => {
                  e.stopPropagation();
                  deleteList(list.id);
                }}
                title="Delete list"
                type="button"
              >
                <svg width="11" height="11" 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>

        {/* Custom Tags Section */}
        <div className="sidebar-section">
          <div className="sidebar-section-label">🏷️ {t("tags") || "Tags"}</div>
          {tags.map((tag) => (
            <div
              key={tag.id}
              className={`sidebar-item${selectedTag === tag.name ? " active" : ""}`}
              onClick={() => onTagSelect(selectedTag === tag.name ? null : tag.name)}
            >
              <span style={{ color: tag.color, fontSize: 13 }}>#</span>
              <span className="item-label">{tag.name}</span>
            </div>
          ))}
        </div>

        {/* Trash Smart List */}
        <div className="sidebar-section">
          <div
            className={`sidebar-item${isTrashActive ? " active" : ""}`}
            id="trash-menu-btn"
            onClick={onTrashSelect}
            style={{ color: isTrashActive ? "var(--danger)" : "var(--text-secondary)" }}
          >
            <span style={{ fontSize: 14 }}>🗑️</span>
            <span className="item-label">{t("trash") || "Trash"}</span>
            {trashCount > 0 && <span className="item-count" style={{ color: "var(--danger)" }}>{trashCount}</span>}
          </div>
        </div>

        {/* New list form */}
        {showNewList ? (
          <div style={{ padding: "4px 10px" }}>
            <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} type="button">
                {t("create")}
              </button>
              <button className="btn btn-ghost btn-sm" onClick={() => setShowNewList(false)} type="button">
                {t("cancel")}
              </button>
            </div>
          </div>
        ) : (
          <button id="new-list-btn" className="sidebar-add-btn" onClick={() => setShowNewList(true)} type="button">
            <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>
        )}
      </nav>

      {/* User footer with Profile Menu containing Settings & Import */}
      <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>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ opacity: 0.5 }}>
            <polyline points="6 9 12 15 18 9" />
          </svg>

          {/* User Popover Menu */}
          {userMenuOpen && (
            <div className="dropdown" style={{ bottom: "calc(100% + 6px)", left: 0, right: 0, marginBottom: 0 }}>
              {/* Settings Action */}
              <div
                className="dropdown-item"
                id="sidebar-settings-menu-item"
                onClick={(e) => {
                  e.stopPropagation();
                  setShowSettings(true);
                  setUserMenuOpen(false);
                }}
              >
                ⚙️ {t("settingsModalTitle") || "Settings"}
              </div>

              {/* Import Action */}
              <div
                className="dropdown-item"
                id="sidebar-import-menu-item"
                onClick={(e) => {
                  e.stopPropagation();
                  setShowImport(true);
                  setImportListId(lists[0]?.id || "");
                  setUserMenuOpen(false);
                }}
              >
                📥 {t("importTasks")}
              </div>

              <div className="context-menu-divider" />

              {isDemo ? (
                <div
                  className="dropdown-item"
                  onClick={() => { window.location.href = "/login"; }}
                >
                  🚪 {t("signIn")}
                </div>
              ) : (
                <div className="dropdown-item danger" id="signout-btn" onClick={() => signOut({ callbackUrl: "/login" })}>
                  🚪 {t("signOut")}
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Context Menu on List */}
      {contextMenu && (
        <ContextMenu
          x={contextMenu.x}
          y={contextMenu.y}
          items={getListContextMenuItems(contextMenu.listId)}
          onClose={() => setContextMenu(null)}
        />
      )}

      {/* Settings Modal */}
      <SettingsModal
        isOpen={showSettings}
        onClose={() => setShowSettings(false)}
        user={user}
        isDemo={isDemo}
      />

      {/* 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)} type="button">{t("cancel")}</button>
              <button id="import-submit-btn" className="btn btn-primary" onClick={handleImport} disabled={importing} type="button">
                {importing ? t("importing") : t("importBtn")}
              </button>
            </div>
          </div>
        </div>
      )}
    </aside>
  );
}