import { useState, useEffect } from "react";
import {
  Package,
  TrendingUp,
  Headphones,
  Home,
  Megaphone,
  Search,
  Clock,
  ChevronDown,
  Sparkles,
  Mail
} from "lucide-react";
import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar,
} from "@/components/ui/sidebar";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { supabase } from "@/integrations/supabase/client";
import { cn } from "@/lib/utils";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";

interface AdminSidebarProps {
  activeTab: string;
  onTabChange: (tab: string) => void;
}

interface AgentTask {
  id: string;
  title: string;
  status: string;
  agent_type: string;
  priority: string;
  created_at: string;
}

const agentItems = [
  { id: "create-task", title: "新任务", icon: Sparkles, color: "text-primary" },
  { id: "home", title: "店长", icon: Home, color: "text-amber-500" },
  { id: "transactions", title: "财务", icon: TrendingUp, color: "text-emerald-500" },
  { id: "products", title: "商品", icon: Package, color: "text-blue-500" },
  { id: "marketing", title: "营销", icon: Megaphone, color: "text-purple-500" },
  { id: "aftersales", title: "客服", icon: Headphones, color: "text-rose-500" },
  { id: "email", title: "邮件", icon: Mail, color: "text-cyan-500" },
];

export function AdminSidebar({ activeTab, onTabChange }: AdminSidebarProps) {
  const { state } = useSidebar();
  const isCollapsed = state === "collapsed";
  const [searchQuery, setSearchQuery] = useState("");
  const [tasks, setTasks] = useState<AgentTask[]>([]);
  const [isHistoryOpen, setIsHistoryOpen] = useState(true);

  // 获取Agent任务列表
  useEffect(() => {
    const fetchTasks = async () => {
      const { data, error } = await supabase
        .from('goals')
        .select('id, title, status, agent_type, priority, created_at')
        .order('created_at', { ascending: false })
        .limit(15);

      if (!error && data) {
        setTasks(data);
      }
    };

    fetchTasks();

    // 实时订阅任务变更
    const channel = supabase
      .channel('agent-tasks')
      .on('postgres_changes', {
        event: '*',
        schema: 'public',
        table: 'goals'
      }, () => {
        // 重新获取任务列表
        fetchTasks();
      })
      .subscribe();

    return () => {
      supabase.removeChannel(channel);
    };
  }, []);

  // 过滤任务
  const filteredTasks = tasks.filter(item =>
    item.title.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // 获取状态颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'bg-emerald-500';
      case 'in_progress': return 'bg-blue-500';
      case 'pending': return 'bg-amber-500';
      default: return 'bg-muted-foreground';
    }
  };

  // 获取Agent颜色
  const getAgentColor = (agentType: string) => {
    switch (agentType) {
      case 'manager': return 'text-amber-500';
      case 'finance': return 'text-emerald-500';
      case 'product': return 'text-blue-500';
      case 'marketing': return 'text-purple-500';
      case 'service': return 'text-rose-500';
      default: return 'text-muted-foreground';
    }
  };

  if (isCollapsed) {
    return (
      <Sidebar className="w-14" collapsible="icon">
        <SidebarContent className="py-2">
          <SidebarGroup>
            <SidebarGroupContent>
              <SidebarMenu>
                {agentItems.map((item) => (
                  <SidebarMenuItem key={item.id}>
                    <SidebarMenuButton
                      onClick={() => onTabChange(item.id)}
                      isActive={activeTab === item.id}
                      className="hover:bg-muted/50"
                      tooltip={item.title}
                    >
                      <item.icon className={cn("h-4 w-4", item.color)} />
                    </SidebarMenuButton>
                  </SidebarMenuItem>
                ))}
              </SidebarMenu>
            </SidebarGroupContent>
          </SidebarGroup>
        </SidebarContent>
      </Sidebar>
    );
  }

  return (
    <Sidebar className="w-64 border-r" collapsible="icon">
      <SidebarContent className="flex flex-col h-full">
        {/* 顶部操作区 - 与主header高度对齐 */}
        <div className="h-[49px] px-3 flex items-center border-b">
          {/* 搜索框 */}
          <div className="relative w-full">
            <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="搜索历史..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-8 h-8 text-sm"
            />
          </div>
        </div>

        {/* Agent 导航 */}
        <SidebarGroup className="py-2">
          <SidebarGroupLabel className="px-3 text-xs text-muted-foreground">
            智能助理
          </SidebarGroupLabel>
          <SidebarGroupContent>
            <SidebarMenu>
              {agentItems.map((item) => (
                <SidebarMenuItem key={item.id}>
                  <SidebarMenuButton
                    onClick={() => onTabChange(item.id)}
                    isActive={activeTab === item.id}
                    className={cn(
                      "hover:bg-muted/50 mx-2 rounded-md",
                      activeTab === item.id && "bg-muted"
                    )}
                  >
                    <item.icon className={cn("h-4 w-4", item.color)} />
                    <span>{item.title}</span>
                  </SidebarMenuButton>
                </SidebarMenuItem>
              ))}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>

        {/* 历史记录 */}
        <div className="flex-1 min-h-0 border-t flex flex-col overflow-hidden">
          <Collapsible
            open={isHistoryOpen}
            onOpenChange={setIsHistoryOpen}
            className="flex-1 min-h-0 flex flex-col"
          >
            <CollapsibleTrigger className="flex items-center justify-between w-full px-3 py-2 text-xs text-muted-foreground hover:bg-muted/50 shrink-0">
              <div className="flex items-center gap-1.5">
                <Clock className="h-3.5 w-3.5" />
                <span>最近任务</span>
              </div>
              <ChevronDown className={cn(
                "h-3.5 w-3.5 transition-transform",
                isHistoryOpen && "rotate-180"
              )} />
            </CollapsibleTrigger>
            <CollapsibleContent className="flex-1 min-h-0 overflow-hidden">
              <ScrollArea className="h-full">
                <div className="px-2 pb-2 space-y-0.5">
                  {filteredTasks.length === 0 ? (
                    <div className="px-2 py-4 text-xs text-muted-foreground text-center">
                      {searchQuery ? "没有找到匹配的任务" : "暂无Agent任务"}
                    </div>
                  ) : (
                    filteredTasks.map((item) => (
                      <button
                        key={item.id}
                        className="w-full text-left px-2 py-1.5 rounded-md hover:bg-muted/50 group transition-colors"
                        onClick={() => {
                          // 根据agent_type切换到对应的tab
                          const tabMap: Record<string, string> = {
                            manager: 'home',
                            finance: 'transactions',
                            product: 'products',
                            marketing: 'marketing',
                            service: 'aftersales',
                            email: 'email'
                          };
                          onTabChange(tabMap[item.agent_type] || 'home');
                        }}
                      >
                        <div className="flex items-start gap-2">
                          <div className={cn("h-2 w-2 rounded-full mt-1.5 shrink-0", getStatusColor(item.status))} />
                          <div className="flex-1 min-w-0">
                            <p className="text-xs truncate">
                              {item.title}
                            </p>
                            <div className="flex items-center gap-1.5 mt-0.5">
                              <span className={cn("text-[10px]", getAgentColor(item.agent_type))}>
                                {item.agent_type === 'manager' ? '店长' :
                                 item.agent_type === 'finance' ? '财务' :
                                 item.agent_type === 'product' ? '商品' :
                                 item.agent_type === 'marketing' ? '营销' :
                                 item.agent_type === 'service' ? '客服' :
                                 item.agent_type === 'email' ? '邮件' : item.agent_type}
                              </span>
                              <span className="text-[10px] text-muted-foreground">
                                {formatDistanceToNow(new Date(item.created_at), { 
                                  addSuffix: true,
                                  locale: zhCN
                                })}
                              </span>
                            </div>
                          </div>
                        </div>
                      </button>
                    ))
                  )}
                </div>
              </ScrollArea>
            </CollapsibleContent>
          </Collapsible>
        </div>

      </SidebarContent>
    </Sidebar>
  );
}
