"use client";

import { useState, useEffect, useCallback } from "react";
import { Article, Folder } from "@/lib/types";
import { useReaderSettings, useTTSSettings } from "@/hooks/useSettings";
import { useTTS } from "@/hooks/useTTS";
import { ArticleList } from "@/components/ArticleList";
import { Reader } from "@/components/Reader";
import { SettingsPanel } from "@/components/SettingsPanel";
import { TTSControls } from "@/components/TTSControls";
import { AddArticle } from "@/components/AddArticle";
import {
  BookOpen,
  Star,
  Archive,
  Menu,
  Search,
  FolderIcon,
  Settings,
  BarChart3,
  X,
} from "lucide-react";
import Link from "next/link";

type FilterType = "all" | "favorites" | "archived" | "folder" | "search";

export default function Home() {
  const [articles, setArticles] = useState<Article[]>([]);
  const [folders, setFolders] = useState<Folder[]>([]);
  const [selectedArticle, setSelectedArticle] = useState<Article | null>(null);
  const [filter, setFilter] = useState<FilterType>("all");
  const [selectedFolderId, setSelectedFolderId] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [isSearching, setIsSearching] = useState(false);
  const [isSettingsOpen, setIsSettingsOpen] = useState(false);
  const [isSidebarOpen, setIsSidebarOpen] = useState(true);
  const [isLoading, setIsLoading] = useState(true);
  const [stats, setStats] = useState<{ streak: number; todayCount: number } | null>(null);

  const [readerSettings, setReaderSettings] = useReaderSettings();
  const [ttsSettings, setTTSSettings] = useTTSSettings();

  const tts = useTTS({
    settings: ttsSettings,
    text: selectedArticle?.textContent || "",
  });

  // Apply theme (with auto-scheduling)
  useEffect(() => {
    if (readerSettings.autoTheme) {
      const hour = new Date().getHours();
      const isDaytime = hour >= 6 && hour < 18;
      const theme = isDaytime ? readerSettings.dayTheme : readerSettings.nightTheme;
      document.documentElement.setAttribute("data-theme", theme);
    } else {
      document.documentElement.setAttribute("data-theme", readerSettings.theme);
    }
  }, [readerSettings]);

  // Fetch articles
  const fetchArticles = useCallback(async () => {
    try {
      let url = `/api/articles?filter=${filter}`;
      if (filter === "folder" && selectedFolderId) {
        url = `/api/articles?folderId=${selectedFolderId}`;
      }
      const response = await fetch(url);
      if (response.ok) {
        const data = await response.json();
        setArticles(data);
      }
    } catch (error) {
      console.error("Failed to fetch articles:", error);
    } finally {
      setIsLoading(false);
    }
  }, [filter, selectedFolderId]);

  // Fetch folders
  const fetchFolders = useCallback(async () => {
    try {
      const response = await fetch("/api/folders");
      if (response.ok) {
        setFolders(await response.json());
      }
    } catch (error) {
      console.error("Failed to fetch folders:", error);
    }
  }, []);

  // Fetch stats
  const fetchStats = useCallback(async () => {
    try {
      const response = await fetch("/api/stats?days=7");
      if (response.ok) {
        const data = await response.json();
        const today = new Date().toISOString().split("T")[0];
        const todayStats = data.daily.find((d: { date: string }) => d.date === today);
        setStats({
          streak: data.streak,
          todayCount: todayStats?.articlesRead || 0,
        });
      }
    } catch (error) {
      console.error("Failed to fetch stats:", error);
    }
  }, []);

  useEffect(() => {
    fetchArticles();
    fetchFolders();
    fetchStats();
  }, [fetchArticles, fetchFolders, fetchStats]);

  // Search
  const handleSearch = async () => {
    if (!searchQuery.trim()) {
      setFilter("all");
      return;
    }

    setIsSearching(true);
    try {
      const response = await fetch(`/api/search?q=${encodeURIComponent(searchQuery)}`);
      if (response.ok) {
        const data = await response.json();
        setArticles(data);
        setFilter("search");
      }
    } catch (error) {
      console.error("Search failed:", error);
    } finally {
      setIsSearching(false);
    }
  };

  // Add article
  const handleAddArticle = async (url: string) => {
    const response = await fetch("/api/articles", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ url }),
    });

    if (!response.ok) {
      const data = await response.json();
      throw new Error(data.error || "Failed to add article");
    }

    await fetchArticles();
    fetchStats();
  };

  // Toggle favorite
  const handleToggleFavorite = async (id: string, isFavorite: boolean) => {
    await fetch(`/api/articles/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ isFavorite }),
    });

    setArticles((prev) =>
      prev.map((a) => (a.id === id ? { ...a, isFavorite } : a))
    );

    if (selectedArticle?.id === id) {
      setSelectedArticle((prev) => (prev ? { ...prev, isFavorite } : null));
    }
  };

  // Toggle archive
  const handleToggleArchive = async (id: string, isArchived: boolean) => {
    await fetch(`/api/articles/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ isArchived }),
    });

    await fetchArticles();
    fetchStats();

    if (selectedArticle?.id === id) {
      setSelectedArticle(null);
    }
  };

  // Delete article
  const handleDelete = async (id: string) => {
    await fetch(`/api/articles/${id}`, { method: "DELETE" });
    await fetchArticles();

    if (selectedArticle?.id === id) {
      setSelectedArticle(null);
    }
  };

  // Reading view
  if (selectedArticle) {
    return (
      <>
        <Reader
          article={selectedArticle}
          settings={readerSettings}
          onBack={() => {
            tts.stop();
            setSelectedArticle(null);
          }}
          onToggleFavorite={() =>
            handleToggleFavorite(selectedArticle.id, !selectedArticle.isFavorite)
          }
          onToggleArchive={() => {
            handleToggleArchive(selectedArticle.id, !selectedArticle.isArchived);
          }}
          onDelete={() => {
            handleDelete(selectedArticle.id);
          }}
          onOpenSettings={() => setIsSettingsOpen(true)}
        >
          <TTSControls
            isPlaying={tts.isPlaying}
            isPaused={tts.isPaused}
            isLoading={tts.isLoading}
            currentTime={tts.currentTime}
            duration={tts.duration}
            progress={tts.progress}
            onPlay={tts.play}
            onPause={tts.pause}
            onResume={tts.resume}
            onStop={tts.stop}
            onSeek={tts.seek}
          />
        </Reader>
        <SettingsPanel
          isOpen={isSettingsOpen}
          onClose={() => setIsSettingsOpen(false)}
          readerSettings={readerSettings}
          onReaderSettingsChange={setReaderSettings}
          ttsSettings={ttsSettings}
          onTTSSettingsChange={setTTSSettings}
          availableVoices={tts.voices}
        />
      </>
    );
  }

  // List view
  return (
    <div className="min-h-screen flex">
      {/* Sidebar */}
      <aside
        className={`${
          isSidebarOpen ? "w-64" : "w-0"
        } flex-shrink-0 border-r border-[var(--border)] transition-all duration-200 overflow-hidden`}
      >
        <div className="w-64 h-full flex flex-col">
          <div className="p-4 border-b border-[var(--border)]">
            <h1 className="text-xl font-bold flex items-center gap-2">
              <BookOpen className="w-6 h-6" />
              ReadLater
            </h1>
            {stats && stats.streak > 0 && (
              <p className="text-xs text-[var(--muted)] mt-1">
                🔥 {stats.streak} day streak
              </p>
            )}
          </div>

          <nav className="flex-1 p-2 overflow-y-auto">
            {/* Main filters */}
            {[
              { value: "all", label: "All Articles", icon: BookOpen },
              { value: "favorites", label: "Favorites", icon: Star },
              { value: "archived", label: "Archived", icon: Archive },
            ].map(({ value, label, icon: Icon }) => (
              <button
                key={value}
                onClick={() => {
                  setFilter(value as FilterType);
                  setSelectedFolderId(null);
                  setSearchQuery("");
                }}
                className={`w-full flex items-center gap-3 px-4 py-3 rounded-lg transition-colors ${
                  filter === value && !selectedFolderId
                    ? "bg-[var(--accent)] text-white"
                    : "text-[var(--foreground)] hover:bg-[var(--surface)]"
                }`}
              >
                <Icon className="w-5 h-5" />
                {label}
              </button>
            ))}

            {/* Folders */}
            {folders.length > 0 && (
              <div className="mt-4 pt-4 border-t border-[var(--border)]">
                <p className="px-4 py-2 text-xs text-[var(--muted)] uppercase tracking-wide">
                  Folders
                </p>
                {folders.map((folder) => (
                  <button
                    key={folder.id}
                    onClick={() => {
                      setFilter("folder");
                      setSelectedFolderId(folder.id);
                      setSearchQuery("");
                    }}
                    className={`w-full flex items-center gap-3 px-4 py-3 rounded-lg transition-colors ${
                      selectedFolderId === folder.id
                        ? "bg-[var(--accent)] text-white"
                        : "text-[var(--foreground)] hover:bg-[var(--surface)]"
                    }`}
                  >
                    <FolderIcon
                      className="w-5 h-5"
                      style={{ color: selectedFolderId === folder.id ? "white" : folder.color }}
                    />
                    {folder.name}
                  </button>
                ))}
              </div>
            )}
          </nav>

          <div className="p-2 border-t border-[var(--border)]">
            <Link
              href="/settings"
              className="w-full flex items-center gap-3 px-4 py-3 rounded-lg text-[var(--muted)] hover:text-[var(--foreground)] hover:bg-[var(--surface)] transition-colors"
            >
              <Settings className="w-5 h-5" />
              Settings
            </Link>
          </div>
        </div>
      </aside>

      {/* Main content */}
      <main className="flex-1 flex flex-col min-w-0">
        <header className="flex items-center gap-4 px-4 py-3 border-b border-[var(--border)]">
          <button
            onClick={() => setIsSidebarOpen(!isSidebarOpen)}
            className="p-2 rounded hover:bg-[var(--surface)] transition-colors"
          >
            <Menu className="w-5 h-5" />
          </button>

          {/* Search */}
          <div className="flex-1 flex items-center gap-2 max-w-md">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[var(--muted)]" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && handleSearch()}
                placeholder="Search articles..."
                className="w-full pl-10 pr-4 py-2 rounded-lg border border-[var(--border)] bg-[var(--background)] text-sm"
              />
              {searchQuery && (
                <button
                  onClick={() => {
                    setSearchQuery("");
                    setFilter("all");
                    fetchArticles();
                  }}
                  className="absolute right-3 top-1/2 -translate-y-1/2"
                >
                  <X className="w-4 h-4 text-[var(--muted)]" />
                </button>
              )}
            </div>
          </div>

          <span className="text-[var(--muted)] text-sm">
            {articles.length} articles
          </span>
        </header>

        <AddArticle onAdd={handleAddArticle} />

        <div className="flex-1 overflow-y-auto">
          {isLoading || isSearching ? (
            <div className="flex items-center justify-center h-64">
              <div className="animate-pulse text-[var(--muted)]">
                {isSearching ? "Searching..." : "Loading..."}
              </div>
            </div>
          ) : (
            <ArticleList
              articles={articles}
              onSelect={setSelectedArticle}
              onToggleFavorite={handleToggleFavorite}
              onToggleArchive={handleToggleArchive}
              onDelete={handleDelete}
            />
          )}
        </div>
      </main>

      <SettingsPanel
        isOpen={isSettingsOpen}
        onClose={() => setIsSettingsOpen(false)}
        readerSettings={readerSettings}
        onReaderSettingsChange={setReaderSettings}
        ttsSettings={ttsSettings}
        onTTSSettingsChange={setTTSSettings}
        availableVoices={tts.voices}
      />
    </div>
  );
}
