import { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { supabase } from "@/integrations/supabase/client";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";
import { 
  CheckCircle2, XCircle, Package, Megaphone, 
  HeadphonesIcon, Loader2 
} from "lucide-react";

interface CompletedTask {
  id: string;
  type: 'aftersales' | 'marketing' | 'product';
  title: string;
  description: string;
  status: 'approved' | 'rejected';
  completedAt: Date;
  agent?: string;
}

interface CompletedTasksDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function CompletedTasksDialog({ open, onOpenChange }: CompletedTasksDialogProps) {
  const [tasks, setTasks] = useState<CompletedTask[]>([]);
  const [loading, setLoading] = useState(true);
  const [completedCount, setCompletedCount] = useState(0);

  useEffect(() => {
    if (open) {
      fetchCompletedTasks();
    }
  }, [open]);

  const fetchCompletedTasks = async () => {
    setLoading(true);
    try {
      const allTasks: CompletedTask[] = [];

      // 获取已处理的售后请求
      const { data: afterSales } = await supabase
        .from('after_sales_requests')
        .select('id, type, reason, description, status, processed_at, updated_at')
        .in('status', ['approved', 'rejected'])
        .order('updated_at', { ascending: false })
        .limit(20);

      afterSales?.forEach(item => {
        allTasks.push({
          id: item.id,
          type: 'aftersales',
          title: `${item.type === 'refund' ? '退款' : item.type === 'return' ? '退货' : '换货'}申请`,
          description: item.reason || item.description,
          status: item.status as 'approved' | 'rejected',
          completedAt: new Date(item.processed_at || item.updated_at),
          agent: '客服Agent'
        });
      });

      // 获取已处理的营销活动
      const { data: campaigns } = await supabase
        .from('marketing_campaigns')
        .select('id, name, description, status, reviewed_at, updated_at')
        .in('status', ['approved', 'rejected'])
        .order('updated_at', { ascending: false })
        .limit(20);

      campaigns?.forEach(item => {
        allTasks.push({
          id: item.id,
          type: 'marketing',
          title: item.name,
          description: item.description || '',
          status: item.status as 'approved' | 'rejected',
          completedAt: new Date(item.reviewed_at || item.updated_at),
          agent: '营销Agent'
        });
      });

      // 按完成时间排序
      allTasks.sort((a, b) => b.completedAt.getTime() - a.completedAt.getTime());
      
      setTasks(allTasks);
      setCompletedCount(allTasks.length);
    } catch (error) {
      console.error('获取已完成任务失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const getTypeIcon = (type: CompletedTask['type']) => {
    switch (type) {
      case 'aftersales':
        return <HeadphonesIcon className="h-4 w-4" />;
      case 'marketing':
        return <Megaphone className="h-4 w-4" />;
      case 'product':
        return <Package className="h-4 w-4" />;
    }
  };

  const getTypeName = (type: CompletedTask['type']) => {
    switch (type) {
      case 'aftersales': return '售后';
      case 'marketing': return '营销';
      case 'product': return '商品';
    }
  };

  const filterByType = (type?: CompletedTask['type']) => {
    if (!type) return tasks;
    return tasks.filter(t => t.type === type);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[80vh]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <CheckCircle2 className="h-5 w-5 text-emerald-500" />
            已协调完成 ({completedCount})
          </DialogTitle>
        </DialogHeader>

        {loading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
          </div>
        ) : tasks.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
            <CheckCircle2 className="h-12 w-12 mb-3 opacity-20" />
            <p>暂无已完成的协调任务</p>
          </div>
        ) : (
          <Tabs defaultValue="all" className="w-full">
            <TabsList className="grid w-full grid-cols-4">
              <TabsTrigger value="all">全部 ({tasks.length})</TabsTrigger>
              <TabsTrigger value="aftersales">
                售后 ({filterByType('aftersales').length})
              </TabsTrigger>
              <TabsTrigger value="marketing">
                营销 ({filterByType('marketing').length})
              </TabsTrigger>
              <TabsTrigger value="product">
                商品 ({filterByType('product').length})
              </TabsTrigger>
            </TabsList>

            {['all', 'aftersales', 'marketing', 'product'].map(tab => (
              <TabsContent key={tab} value={tab} className="mt-4">
                <ScrollArea className="h-[400px]">
                  <div className="space-y-3 pr-4">
                    {filterByType(tab === 'all' ? undefined : tab as CompletedTask['type']).map(task => (
                      <div 
                        key={task.id}
                        className="p-3 rounded-lg border bg-card hover:bg-accent/50 transition-colors"
                      >
                        <div className="flex items-start justify-between gap-3">
                          <div className="flex items-start gap-3">
                            <div className={`p-2 rounded-full ${
                              task.status === 'approved' 
                                ? 'bg-emerald-500/10 text-emerald-500' 
                                : 'bg-red-500/10 text-red-500'
                            }`}>
                              {task.status === 'approved' 
                                ? <CheckCircle2 className="h-4 w-4" />
                                : <XCircle className="h-4 w-4" />
                              }
                            </div>
                            <div className="flex-1 min-w-0">
                              <div className="flex items-center gap-2 mb-1">
                                <h4 className="font-medium text-sm">{task.title}</h4>
                                <Badge variant="outline" className="text-xs">
                                  {getTypeIcon(task.type)}
                                  <span className="ml-1">{getTypeName(task.type)}</span>
                                </Badge>
                              </div>
                              <p className="text-xs text-muted-foreground line-clamp-2">
                                {task.description}
                              </p>
                              <div className="flex items-center gap-2 mt-2 text-xs text-muted-foreground">
                                {task.agent && (
                                  <span className="text-primary">{task.agent}</span>
                                )}
                                <span>•</span>
                                <span>
                                  {formatDistanceToNow(task.completedAt, { 
                                    addSuffix: true, 
                                    locale: zhCN 
                                  })}
                                </span>
                              </div>
                            </div>
                          </div>
                          <Badge 
                            variant={task.status === 'approved' ? 'default' : 'destructive'}
                            className="shrink-0"
                          >
                            {task.status === 'approved' ? '已通过' : '已拒绝'}
                          </Badge>
                        </div>
                      </div>
                    ))}
                  </div>
                </ScrollArea>
              </TabsContent>
            ))}
          </Tabs>
        )}
      </DialogContent>
    </Dialog>
  );
}
