import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/components/ui/use-toast';
import { autoPublishApi } from '@/api/autoPublishApi';
import { useAuth } from '@/contexts/AuthContext';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { 
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogFooter
} from '@/components/ui/dialog';
import { 
  Clock, 
  Plus, 
  Play,
  Pause,
  Trash2,
  Settings,
  Calendar,
  Target,
  Zap
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

export default function AutoPublish() {
  const { user } = useAuth();
  const { toast } = useToast();
  const [tasks, setTasks] = useState([]);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [taskUpdateInterval, setTaskUpdateInterval] = useState(null);
  const [newTask, setNewTask] = useState({
    name: '定时发布',
    platform: 'xiaohongshu',
    app_name: '小红书批量发布制作视频_商品_其它_新版2.0.0',
    version: '当前最新版本',
    frequency: 'daily',
    scheduled_times: ['09:00'],
    start_date: '',
    end_date: '',
    is_active: true,
    content_filter: { status: 'approved' },
    advanced_settings: {
      max_runs: 0,
      retry_on_failure: true,
      notification_enabled: true
    }
  });

  const timeSlots = [
    '00:00', '01:00', '02:00', '03:00', '04:00', '05:00',
    '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
    '12:00', '13:00', '14:00', '15:00', '16:00', '17:00',
    '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'
  ];

  // 更新任务状态的函数
  const updateTaskStatus = async (taskId) => {
    try {
      const response = await autoPublishApi.getTaskStatus(taskId);
      if (response.success) {
        setTasks(prev => prev.map(task => {
          if (task.id === taskId) {
            const isCompleted = response.total_tasks === (response.success_count + response.failure_count);
            return {
              ...task,
              status: isCompleted ? 'completed' : 'running',
              total_runs: response.total_tasks || 0,
              success_runs: response.success_count || 0,
              failed_runs: response.failure_count || 0,
              next_run: response.next_run,
              last_run: response.last_run
            };
          }
          return task;
        }));

        // 如果任务完成，显示通知
        if (response.total_tasks === (response.success_count + response.failure_count)) {
          toast({
            title: "任务完成",
            description: `发布完成: ${response.success_count}个成功, ${response.failure_count}个失败`,
            variant: response.failure_count === 0 ? "success" : "warning",
          });
          
          // 清除该任务的更新定时器
          if (taskUpdateInterval) {
            clearInterval(taskUpdateInterval);
            setTaskUpdateInterval(null);
          }
        }
      }
    } catch (error) {
      console.error('更新任务状态失败:', error);
    }
  };

  // 定时更新所有任务状态
  const updateAllTasks = async () => {
    try {
      const updatedTasks = await autoPublishApi.getTaskList(user?.id);
      setTasks(updatedTasks);
    } catch (error) {
      console.error('更新任务列表失败:', error);
    }
  };

  useEffect(() => {
    loadTasks();
    setDefaultDate();

    // 设置定时更新任务列表
    const intervalId = setInterval(updateAllTasks, 2000);

    // 清理函数
    return () => {
      clearInterval(intervalId);
      if (taskUpdateInterval) {
        clearInterval(taskUpdateInterval);
      }
    };
  }, [user]);

  // 获取日期范围限制
  const getDateConstraints = () => {
    const today = new Date();
    const twoWeeksLater = new Date(today);
    twoWeeksLater.setDate(today.getDate() + 14);
    
    return {
      minDate: today.toISOString().split('T')[0],
      maxDate: twoWeeksLater.toISOString().split('T')[0]
    };
  };

  const setDefaultDate = () => {
    const { minDate, maxDate } = getDateConstraints();
    
    setNewTask(prev => ({
      ...prev,
      start_date: minDate,
      end_date: maxDate
    }));
  };

  const loadTasks = async () => {
    try {
      const tasks = await autoPublishApi.getTaskList(user?.id);
      setTasks(tasks);
    } catch (error) {
      console.error('加载任务列表失败:', error);
      toast({
        title: "加载失败",
        description: error.message || "加载任务列表时发生错误",
        variant: "destructive",
      });
      setTasks([]);
    }
  };

  const handleCreateTask = async () => {
    try {
      // 立即关闭弹窗
      setIsCreateModalOpen(false);

      // 创建本地任务记录
      const newTaskWithId = {
        ...newTask,
        id: Date.now().toString(),
        status: 'running',
        last_run: null,
        next_run: new Date().toISOString(),
        total_runs: 0,
        success_runs: 0,
        failed_runs: 0
      };
      
      // 立即添加任务到列表
      setTasks(prev => [newTaskWithId, ...prev]);

      // 显示创建中的提示
      toast({
        title: "创建中",
        description: "正在创建自动发布任务，请稍候...",
        variant: "default",
      });

      // 调用自动发布API
      const response = await autoPublishApi.createAutoPublishTask({
        ...newTask,
        scheduled_time: newTask.scheduled_times[0], // 使用第一个计划时间
        platform: newTask.platform,
        content_filter: { status: 'approved' }
      }, user?.id);

      if (response.success) {
        // 更新任务状态
        const updatedTaskId = response.task_id || newTaskWithId.id;
        setTasks(prev => prev.map(task => 
          task.id === newTaskWithId.id 
            ? { 
                ...task, 
                id: updatedTaskId,
                total_runs: response.total_tasks || 0,
                success_runs: 0,
                failed_runs: 0
              }
            : task
        ));
        
        toast({
          title: "创建成功",
          description: response.message || "自动发布任务已创建，系统将按计划执行发布。",
          variant: "success",
        });

        // 设置定时更新任务状态
        const intervalId = setInterval(() => updateTaskStatus(updatedTaskId), 2000);
        setTaskUpdateInterval(intervalId);

        // 重置表单
        setNewTask({
          name: '定时发布',
          platform: 'xiaohongshu',
          app_name: '小红书批量发布制作视频_商品_其它_新版2.0.0',
          version: '当前最新版本',
          frequency: 'daily',
          scheduled_times: ['09:00'],
          start_date: '',
          end_date: '',
          is_active: true,
          content_filter: { status: 'approved' },
          advanced_settings: {
            max_runs: 0,
            retry_on_failure: true,
            notification_enabled: true
          }
        });
        setDefaultDate();
      }
    } catch (error) {
      console.error('创建自动发布任务失败:', error);
      toast({
        title: "创建失败",
        description: error.response?.data?.detail || "创建自动发布任务时发生错误",
        variant: "destructive",
      });
    }
  };

  const toggleTaskStatus = async (taskId, currentStatus) => {
    setTasks(prev => prev.map(task => 
      task.id === taskId 
        ? { ...task, is_active: !task.is_active, status: !task.is_active ? 'running' : 'paused' }
        : task
    ));
  };

  const deleteTask = async (taskId) => {
    setTasks(prev => prev.filter(task => task.id !== taskId));
  };

  const addTimeSlot = (time) => {
    if (!newTask.scheduled_times.includes(time)) {
      setNewTask(prev => ({
        ...prev,
        scheduled_times: [...prev.scheduled_times, time]
      }));
    }
  };

  const removeTimeSlot = (time) => {
    setNewTask(prev => ({
      ...prev,
      scheduled_times: prev.scheduled_times.filter(t => t !== time)
    }));
  };

  const getPlatformName = (platform) => {
    const platforms = {
      xiaohongshu: '小红书',
      douyin: '抖音',
      weibo: '微博',
      bilibili: 'B站'
    };
    return platforms[platform] || platform;
  };

  const getFrequencyName = (frequency) => {
    const frequencies = {
      daily: '每日',
      weekly: '每周',
      monthly: '每月',
      custom: '自定义'
    };
    return frequencies[frequency] || frequency;
  };

  const getStatusColor = (status) => {
    const colors = {
      running: 'bg-green-100 text-green-700',
      paused: 'bg-yellow-100 text-yellow-700',
      error: 'bg-red-100 text-red-700',
      completed: 'bg-blue-100 text-blue-700'
    };
    return colors[status] || 'bg-gray-100 text-gray-700';
  };

  const getStatusName = (status) => {
    const names = {
      running: '运行中',
      paused: '已暂停',
      error: '错误',
      completed: '已完成'
    };
    return names[status] || status;
  };

  return (
    <div className="p-6">
      <div className="max-w-7xl mx-auto">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-slate-900 mb-2">自动发布</h1>
          <p className="text-slate-600">设置定时发布任务，自动发布内容到各平台</p>
        </div>

        {/* 操作栏 */}
        <div className="flex justify-between items-center mb-6">
          <div className="flex items-center gap-4">
            <Badge variant="secondary" className="bg-blue-100 text-blue-700">
              总计: {tasks.length} 个任务
            </Badge>
            <Badge variant="secondary" className="bg-green-100 text-green-700">
              运行中: {tasks.filter(t => t.status === 'running').length} 个
            </Badge>
          </div>
          
          <Dialog open={isCreateModalOpen} onOpenChange={setIsCreateModalOpen}>
            <DialogTrigger asChild>
              <Button className="bg-blue-600 hover:bg-blue-700">
                <Plus className="w-4 h-4 mr-2" />
                创建任务
              </Button>
            </DialogTrigger>
            
            <DialogContent className="max-w-2xl">
              <DialogHeader>
                <DialogTitle>创建自动化发布任务</DialogTitle>
              </DialogHeader>
              
              <div className="space-y-6 py-4">
                {/* 基本信息 */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="name">任务名称</Label>
                    <Input
                      id="name"
                      value={newTask.name}
                      onChange={(e) => setNewTask(prev => ({ ...prev, name: e.target.value }))}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="platform">发布平台</Label>
                    <Select value={newTask.platform} onValueChange={(value) => setNewTask(prev => ({ ...prev, platform: value }))}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="xiaohongshu">小红书</SelectItem>
                        <SelectItem value="douyin">抖音</SelectItem>
                        <SelectItem value="weibo">微博</SelectItem>
                        <SelectItem value="bilibili">B站</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                {/* 时间设置 */}
                <div>
                  <Label>发布时间</Label>
                  <div className="mt-2 grid grid-cols-6 gap-2">
                    {timeSlots.map(time => (
                      <Button
                        key={time}
                        variant={newTask.scheduled_times.includes(time) ? "default" : "outline"}
                        size="sm"
                        onClick={() => newTask.scheduled_times.includes(time) ? removeTimeSlot(time) : addTimeSlot(time)}
                      >
                        {time}
                      </Button>
                    ))}
                  </div>
                </div>

                {/* 频率设置 */}
                <div>
                  <Label>发布频率</Label>
                  <RadioGroup value={newTask.frequency} onValueChange={(value) => setNewTask(prev => ({ ...prev, frequency: value }))}>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="daily" id="daily" />
                      <Label htmlFor="daily">每日</Label>
                    </div>
                    {/* <div className="flex items-center space-x-2">
                      <RadioGroupItem value="weekly" id="weekly" />
                      <Label htmlFor="weekly">每周</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="monthly" id="monthly" />
                      <Label htmlFor="monthly">每月</Label>
                    </div> */}
                  </RadioGroup>
                </div>

                {/* 日期范围 */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="start_date">开始日期</Label>
                    <Input
                      id="start_date"
                      type="date"
                      value={newTask.start_date}
                      min={getDateConstraints().minDate}
                      max={getDateConstraints().maxDate}
                      onChange={(e) => {
                        const newStartDate = e.target.value;
                        setNewTask(prev => ({
                          ...prev,
                          start_date: newStartDate,
                          // 如果结束日期早于开始日期，更新结束日期
                          end_date: prev.end_date < newStartDate ? newStartDate : prev.end_date
                        }));
                      }}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="end_date">结束日期</Label>
                    <Input
                      id="end_date"
                      type="date"
                      value={newTask.end_date}
                      min={newTask.start_date || getDateConstraints().minDate}
                      max={getDateConstraints().maxDate}
                      onChange={(e) => {
                        const newEndDate = e.target.value;
                        setNewTask(prev => ({
                          ...prev,
                          end_date: newEndDate,
                          // 如果开始日期晚于结束日期，更新开始日期
                          start_date: prev.start_date > newEndDate ? newEndDate : prev.start_date
                        }));
                      }}
                    />
                  </div>
                </div>
              </div>
              
              <DialogFooter>
                <Button variant="outline" onClick={() => setIsCreateModalOpen(false)}>
                  取消
                </Button>
                <Button onClick={handleCreateTask}>
                  创建任务
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>
        </div>

        {/* 任务列表 */}
        <div className="grid gap-6">
          <AnimatePresence>
            {tasks.map((task) => (
              <motion.div
                key={task.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                transition={{ duration: 0.3 }}
              >
                <Card>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-500 rounded-lg flex items-center justify-center">
                          <Zap className="w-5 h-5 text-white" />
                        </div>
                        <div>
                          <CardTitle className="text-lg">{task.name}</CardTitle>
                          <p className="text-sm text-slate-500">
                            {getPlatformName(task.platform)} • {getFrequencyName(task.frequency)}
                          </p>
                        </div>
                      </div>
                      
                      <div className="flex items-center gap-2">
                        <Badge className={getStatusColor(task.status)}>
                          {getStatusName(task.status)}
                        </Badge>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => toggleTaskStatus(task.id, task.status)}
                        >
                          {task.is_active ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => deleteTask(task.id)}
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>
                  </CardHeader>
                  
                  <CardContent>
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <div>
                        <p className="text-sm font-medium text-slate-600">发布时间</p>
                        <p className="text-sm text-slate-900">{task.scheduled_times.join(', ')}</p>
                      </div>
                      
                      <div>
                        <p className="text-sm font-medium text-slate-600">执行统计</p>
                        <p className="text-sm text-slate-900">
                          成功: {task.success_runs} | 失败: {task.failed_runs}
                        </p>
                      </div>
                      
                      <div>
                        <p className="text-sm font-medium text-slate-600">下次执行</p>
                        <p className="text-sm text-slate-900">
                          {task.next_run ? new Date(task.next_run).toLocaleString() : '未设置'}
                        </p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </motion.div>
            ))}
          </AnimatePresence>
        </div>
      </div>
    </div>
  );
}