
"use client";

import { Plus, LayoutGrid, List, Loader2, ArrowUpDown } from "lucide-react";
import { useState, useEffect } from "react";
import { useInView } from "react-intersection-observer";
import { useQueryClient } from "@tanstack/react-query";
import { handleError, showSuccess } from "@/lib/services/errorHandler";
import CreateProject from "@/components/project/CreateProject";
import { ProjectData } from '@/types';
import { Button } from "@/components/ui/button";
import { ProjectCard } from "@/components/project/ProjectCard";
import { CreateProjectCard } from "@/components/project/CreateProjectCard";
import { EmptyState } from "@/components/ui/empty-state";
import { LoadingState } from "@/components/ui/loading-state";
import { useConfirm } from "@/components/ui/confirm-dialog";
import { Header } from "@/components/layout/Header";
import { SearchInput } from "@/components/ui/search-input";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Folder } from "lucide-react";
import { useProjectListInfinite, useDeleteProjectMutation, projectKeys } from "@/lib/hooks/useProjects";
import { ProtectedRoute } from "@/components/auth/ProtectedRoute";

const LIMIT = 50;

function HomeContent() {
  const queryClient = useQueryClient();
  const [activeTab, setActiveTab] = useState("my-canvas");
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [showWizard, setShowWizard] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");

  const {
    projects,
    hasNextPage,
    fetchNextPage,
    isFetchingNextPage,
    isLoading,
    refetch,
  } = useProjectListInfinite(LIMIT);

  const deleteProjectMutation = useDeleteProjectMutation();

  const { confirm, ConfirmDialog } = useConfirm();

  const { ref, inView } = useInView({
    threshold: 0,
    rootMargin: '100px',
  });

  useEffect(() => {
    if (inView && hasNextPage && !isFetchingNextPage) {
      fetchNextPage();
    }
  }, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]);

  const handleCreateProject = () => {
    setShowWizard(true);
  };

  const handleWizardClose = () => {
    setShowWizard(false);
    refetch();
  };

  const handleDeleteProject = async (e: React.MouseEvent, projectId: string) => {
    e.preventDefault();
    e.stopPropagation();
    confirm({
      title: '确认删除？',
      description: '确定要删除这个项目吗？此操作无法撤销。',
      variant: 'destructive',
      onConfirm: async () => {
        try {
          await deleteProjectMutation.mutateAsync(projectId);
          showSuccess('删除成功', '项目已成功删除');
        } catch (error) {
          handleError(error, 'DeleteProject', {
            customMessage: '删除项目失败，请重试'
          });
        }
      }
    });
  };

  const handleProjectUpdate = (_updatedProject: ProjectData) => {
    queryClient.invalidateQueries({ queryKey: projectKeys.all });
  };

  // 过滤 projects by search query
  const projectsByTab = projects.filter((project) => {
    if (activeTab === 'my-scripts') {
      return project.type === 'script';
    }
    return project.type !== 'script';
  });

  const filteredProjects = projectsByTab.filter(p => 
      p.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (p.description && p.description.toLowerCase().includes(searchQuery.toLowerCase()))
  );

  return (
    <div className="min-h-screen bg-background text-foreground font-sans selection:bg-primary/30 flex flex-col">
      
      {showWizard && <CreateProject onClose={handleWizardClose} mode={activeTab === 'my-scripts' ? 'script' : 'canvas'} />}

      <Header />

      <main className="flex-1 max-w-[1600px] w-full mx-auto px-4 sm:px-6 py-8">
        
        {/* Top Controls: Tabs & Search */}
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
            <div className="flex items-center gap-6">
                <Tabs value={activeTab} onValueChange={setActiveTab} className="w-auto">
                    <TabsList className="bg-transparent p-0 h-auto gap-6">
                        <TabsTrigger 
                            value="my-canvas" 
                            className="bg-transparent p-0 pb-2 rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:text-primary data-[state=active]:shadow-none text-muted-foreground hover:text-foreground transition-colors text-base font-medium"
                        >
                            我的画布
                        </TabsTrigger>
                        <TabsTrigger 
                            value="my-scripts" 
                            className="bg-transparent p-0 pb-2 rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:text-primary data-[state=active]:shadow-none text-muted-foreground hover:text-foreground transition-colors text-base font-medium"
                        >
                            我的剧本
                        </TabsTrigger>
                    </TabsList>
                </Tabs>
            </div>

            <div className="flex items-center gap-3">
                <div className="flex bg-muted/50 rounded-lg p-1 gap-1 mr-2">
                    <Button 
                        variant={viewMode === 'grid' ? 'secondary' : 'ghost'}
                        size="icon"
                        onClick={() => setViewMode('grid')}
                        className="h-8 w-8"
                    >
                        <LayoutGrid size={16} />
                    </Button>
                    <Button 
                        variant={viewMode === 'list' ? 'secondary' : 'ghost'}
                        size="icon"
                        onClick={() => setViewMode('list')}
                        className="h-8 w-8"
                    >
                        <List size={16} />
                    </Button>
                </div>

                <Button variant="ghost" size="sm" className="text-muted-foreground hover:text-foreground gap-1 hidden sm:flex">
                    更新时间
                    <ArrowUpDown size={14} />
                </Button>
                
                <SearchInput 
                    value={searchQuery}
                    onChange={setSearchQuery}
                    placeholder="搜索"
                    className="w-full md:w-64 bg-muted/50 border-border/50 rounded-lg"
                />

                <Button onClick={handleCreateProject} className="bg-blue-600 hover:bg-blue-700 text-white gap-2 rounded-lg">
                    <Plus size={18} />
                    {activeTab === 'my-scripts' ? '新建剧本' : '新建画布'}
                </Button>
            </div>
        </div>

        {/* Project Grid / List */}
        <div>
            {isLoading && projects.length === 0 ? (
                <LoadingState message="加载项目中..." />
            ) : projectsByTab.length === 0 && !searchQuery ? (
                // Empty State
                activeTab === 'my-scripts' ? (
                    <div className="flex flex-col items-center justify-center h-[60vh]">
                        <div className="text-center space-y-4">
                            <div className="bg-muted/30 p-6 rounded-full inline-block">
                                <Folder size={48} className="text-muted-foreground/50" />
                            </div>
                            <h3 className="text-lg font-medium">暂无剧本</h3>
                            <p className="text-muted-foreground max-w-sm mx-auto mb-4">
                                您还没有创建任何剧本。
                            </p>
                            <Button onClick={handleCreateProject} className="bg-blue-600 hover:bg-blue-700 text-white gap-2 rounded-lg">
                                <Plus size={18} />
                                新建剧本
                            </Button>
                        </div>
                    </div>
                ) : (
                    <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6">
                        <CreateProjectCard onClick={handleCreateProject} label="新建画布" />
                    </div>
                )
            ) : (
                <>
                    <div className={
                        viewMode === 'grid' 
                        ? 'grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6' 
                        : 'flex flex-col gap-4'
                    }>
                        {filteredProjects.map((project) => (
                            <ProjectCard 
                                key={project.id} 
                                project={project} 
                                viewMode={viewMode} 
                                onDelete={handleDeleteProject}
                                onUpdate={handleProjectUpdate}
                            />
                        ))}
                    </div>

                    {/* Empty Search Result */}
                    {filteredProjects.length === 0 && searchQuery && (
                        <EmptyState 
                            icon={Folder}
                            title="未找到项目"
                            description={`未找到包含 "${searchQuery}" 的项目`}
                            className="bg-transparent border-dashed"
                        />
                    )}

                    {/* Sentinel for Infinite Scroll */}
                    <div ref={ref} className="mt-8 flex justify-center pb-8 min-h-[50px]">
                        {isFetchingNextPage && projects.length > 0 && (
                            <div className="flex items-center text-muted-foreground">
                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                加载更多...
                            </div>
                        )}
                    </div>
                </>
            )}
        </div>

      </main>

      {/* Confirm Dialog */}
      <ConfirmDialog />
    </div>
  );
}

export default function Home() {
  return (
    <ProtectedRoute>
      <HomeContent />
    </ProtectedRoute>
  );
}
