import React, { useState, useEffect, useRef, useMemo } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Plus, Edit, Trash2, Play, Pause,
  Clock, Activity, CheckCircle2, XCircle, FolderKanban, PlayCircle, FileText, BarChart3, List, Ban
} from 'lucide-react';
import { useToast } from '@/components/ui/use-toast';
import { PaginatedTable, type ColumnDef, type PaginatedTableRef, type SearchFieldDef } from '@/components/ui/paginated-table';
import { getScheduleJobs, getJobCategoryList, pauseJob, resumeJob, triggerJob, disableJob, deleteScheduleJob, enableJob } from './service';
import type { ScheduleJobResponse, ScheduleJobQuery, JobCategoryResponse, JobStatus } from './types';
import CategoryManageDialog from './components/CategoryManageDialog';
import JobLogDialog from './components/JobLogDialog';
import JobEditDialog from './components/JobEditDialog';
import Dashboard from './components/Dashboard';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import dayjs from 'dayjs';

/**
 * 定时任务列表页
 */
const ScheduleJobList: React.FC = () => {
  const { toast } = useToast();
  const tableRef = useRef<PaginatedTableRef<ScheduleJobResponse>>(null);

  // 分类数据
  const [categories, setCategories] = useState<JobCategoryResponse[]>([]);

  // 弹窗状态
  const [categoryDialogOpen, setCategoryDialogOpen] = useState(false);
  const [logDialogOpen, setLogDialogOpen] = useState(false);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [selectedJob, setSelectedJob] = useState<ScheduleJobResponse | null>(null);
  const [editJob, setEditJob] = useState<ScheduleJobResponse | null>(null);
  const [deleteJob, setDeleteJob] = useState<ScheduleJobResponse | null>(null);

  // 加载分类
  const loadCategories = async () => {
    try {
      const result = await getJobCategoryList();
      setCategories(result || []);
    } catch (error) {
      console.error('加载分类失败:', error);
    }
  };

  useEffect(() => {
    loadCategories();
  }, []);

  // 搜索字段定义
  const searchFields: SearchFieldDef[] = useMemo(() => [
    { key: 'jobName', type: 'input', placeholder: '搜索任务名称...', enterSearch: true },
    { key: 'categoryId', type: 'select', placeholder: '全部分类', width: 'w-[200px]', options: categories.map(c => ({ label: c.name, value: c.id })) },
    { key: 'status', type: 'select', placeholder: '全部状态', width: 'w-[150px]', options: [{ label: '启用', value: 'ENABLED' }, { label: '禁用', value: 'DISABLED' }, { label: '暂停', value: 'PAUSED' }] },
  ], [categories]);

  // 状态徽章
  const getStatusBadge = (status: JobStatus) => {
    const statusMap: Record<JobStatus, { variant: 'default' | 'secondary' | 'destructive' | 'outline'; text: string; icon: React.ElementType }> = {
      ENABLED: { variant: 'default', text: '启用', icon: CheckCircle2 },
      DISABLED: { variant: 'secondary', text: '禁用', icon: XCircle },
      PAUSED: { variant: 'outline', text: '暂停', icon: Pause },
    };
    const statusInfo = statusMap[status] || { variant: 'outline', text: status, icon: Clock };
    const Icon = statusInfo.icon;
    return (
      <Badge variant={statusInfo.variant} className="inline-flex items-center gap-1">
        <Icon className="h-3 w-3" />
        {statusInfo.text}
      </Badge>
    );
  };

  // 操作处理函数
  const handlePause = async (record: ScheduleJobResponse) => {
    try {
      await pauseJob(record.id);
      toast({ title: '暂停成功', description: `任务 "${record.jobName}" 已暂停` });
      tableRef.current?.updateRecord(record.id, { status: 'PAUSED' });
    } catch (error) {
      toast({ variant: 'destructive', title: '暂停失败', description: error instanceof Error ? error.message : '未知错误' });
    }
  };

  const handleResume = async (record: ScheduleJobResponse) => {
    try {
      await resumeJob(record.id);
      toast({ title: '恢复成功', description: `任务 "${record.jobName}" 已恢复` });
      tableRef.current?.updateRecord(record.id, { status: 'ENABLED' });
    } catch (error) {
      toast({ variant: 'destructive', title: '恢复失败', description: error instanceof Error ? error.message : '未知错误' });
    }
  };

  const handleTrigger = async (record: ScheduleJobResponse) => {
    try {
      await triggerJob(record.id);
      toast({ title: '触发成功', description: `任务 "${record.jobName}" 已立即触发执行` });
    } catch (error) {
      toast({ variant: 'destructive', title: '触发失败', description: error instanceof Error ? error.message : '未知错误' });
    }
  };

  const handleDisable = async (record: ScheduleJobResponse) => {
    try {
      await disableJob(record.id);
      toast({ title: '禁用成功', description: `任务 "${record.jobName}" 已禁用` });
      tableRef.current?.updateRecord(record.id, { status: 'DISABLED' });
    } catch (error) {
      toast({ variant: 'destructive', title: '禁用失败', description: error instanceof Error ? error.message : '未知错误' });
    }
  };

  const handleEnable = async (record: ScheduleJobResponse) => {
    try {
      await enableJob(record.id);
      toast({ title: '启用成功', description: `任务 "${record.jobName}" 已启用` });
      tableRef.current?.updateRecord(record.id, { status: 'ENABLED' });
    } catch (error) {
      toast({ variant: 'destructive', title: '启用失败', description: error instanceof Error ? error.message : '未知错误' });
    }
  };

  // 列定义
  const columns: ColumnDef<ScheduleJobResponse>[] = useMemo(() => [
    { key: 'id', title: 'ID', dataIndex: 'id', width: '80px' },
    { key: 'jobName', title: '任务名称', width: '180px', dataIndex: 'jobName', className: 'font-medium whitespace-nowrap' },
    { key: 'category', title: '任务分类', width: '120px', className: 'whitespace-nowrap', render: (_, record) => record.category?.name || '-' },
    { key: 'cronExpression', title: 'Cron表达式', width: '150px', className: 'whitespace-nowrap', render: (_, record) => <code className="text-xs bg-muted px-1 py-0.5 rounded">{record.cronExpression}</code> },
    { key: 'beanName', title: 'Bean名称', width: '120px', className: 'whitespace-nowrap', render: (_, record) => <code className="text-xs">{record.beanName}</code> },
    { key: 'methodName', title: '方法名称', width: '120px', className: 'whitespace-nowrap', render: (_, record) => <code className="text-xs">{record.methodName}</code> },
    { key: 'status', title: '状态', width: '100px', className: 'whitespace-nowrap', render: (_, record) => getStatusBadge(record.status) },
    { key: 'lastExecuteTime', title: '上次执行', width: '160px', className: 'text-xs text-muted-foreground whitespace-nowrap', render: (_, record) => record.lastExecuteTime ? dayjs(record.lastExecuteTime).format('YYYY-MM-DD HH:mm:ss') : '-' },
    { key: 'nextExecuteTime', title: '下次执行', width: '160px', className: 'text-xs text-muted-foreground whitespace-nowrap', render: (_, record) => record.nextExecuteTime ? dayjs(record.nextExecuteTime).format('YYYY-MM-DD HH:mm:ss') : '-' },
    { key: 'executeCount', title: '执行次数', width: '100px', className: 'text-center whitespace-nowrap', render: (_, record) => <Badge variant="outline">{record.executeCount || 0}</Badge> },
    {
      key: 'successRate', title: '成功率', width: '90px', className: 'whitespace-nowrap',
      render: (_, record) => {
        if (record.executeCount && record.executeCount > 0) {
          const rate = record.successCount! / record.executeCount;
          return <Badge variant={rate >= 0.9 ? 'default' : rate >= 0.7 ? 'outline' : 'destructive'}>{(rate * 100).toFixed(1)}%</Badge>;
        }
        return <span className="text-muted-foreground">-</span>;
      }
    },
    {
      key: 'actions', title: '操作', width: '240px', sticky: true,
      render: (_, record) => (
        <div className="flex items-center gap-1">
          {record.status === 'ENABLED' && (
            <>
              <Button type="button" variant="ghost" size="icon" className="h-7 w-7" onClick={() => handlePause(record)} title="暂停"><Pause className="h-4 w-4" /></Button>
              <Button type="button" variant="ghost" size="icon" className="h-7 w-7 text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-500 dark:hover:bg-orange-950/20" onClick={() => handleDisable(record)} title="禁用"><Ban className="h-4 w-4" /></Button>
              <Button type="button" variant="ghost" size="icon" className="h-7 w-7 text-green-600 hover:text-green-700 hover:bg-green-50 dark:text-green-500 dark:hover:bg-green-950/20" onClick={() => handleTrigger(record)} title="立即执行"><PlayCircle className="h-4 w-4" /></Button>
            </>
          )}
          {record.status === 'PAUSED' && (
            <>
              <Button type="button" variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleResume(record)} title="恢复"><Play className="h-4 w-4" /></Button>
              <Button type="button" variant="ghost" size="icon" className="h-7 w-7 text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-500 dark:hover:bg-orange-950/20" onClick={() => handleDisable(record)} title="禁用"><Ban className="h-4 w-4" /></Button>
            </>
          )}
          {record.status === 'DISABLED' && (
            <Button type="button" variant="ghost" size="icon" className="h-7 w-7 text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-950/20" onClick={() => handleEnable(record)} title="启用"><CheckCircle2 className="h-4 w-4" /></Button>
          )}
          <Button type="button" variant="ghost" size="icon" className="h-7 w-7 text-destructive hover:text-destructive" onClick={() => { setDeleteJob(record); setDeleteDialogOpen(true); }} title="删除"><Trash2 className="h-4 w-4" /></Button>
          <Button type="button" variant="ghost" size="icon" className="h-7 w-7" onClick={() => { setSelectedJob(record); setLogDialogOpen(true); }} title="查看日志"><FileText className="h-4 w-4" /></Button>
          <Button type="button" variant="ghost" size="icon" className="h-7 w-7" onClick={() => { setEditJob(record); setEditDialogOpen(true); }} title="编辑"><Edit className="h-4 w-4" /></Button>
        </div>
      )
    },
  ], []);

  // 统计数据
  const stats = useMemo(() => {
    const data = tableRef.current?.getData();
    const total = data?.totalElements || 0;
    const enabledCount = data?.content?.filter(d => d.status === 'ENABLED').length || 0;
    const pausedCount = data?.content?.filter(d => d.status === 'PAUSED').length || 0;
    return { total, enabledCount, pausedCount };
  }, [tableRef.current?.getData()]);

  return (
    <div className="p-6">
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-foreground">定时任务管理</h1>
        <p className="text-muted-foreground mt-2">创建和管理定时任务，配置执行计划和参数。</p>
      </div>

      <Tabs defaultValue="list" className="space-y-6">
        <TabsList>
          <TabsTrigger value="list" className="gap-2"><List className="h-4 w-4" />列表视图</TabsTrigger>
          <TabsTrigger value="dashboard" className="gap-2"><BarChart3 className="h-4 w-4" />仪表盘</TabsTrigger>
        </TabsList>

        <TabsContent value="list" className="space-y-6">
          {/* 统计卡片 */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <Card className="bg-gradient-to-br from-blue-500/10 to-blue-500/5 border-blue-500/20">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium text-blue-700">总任务</CardTitle>
                <Activity className="h-4 w-4 text-blue-500" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{stats.total}</div>
                <p className="text-xs text-muted-foreground mt-1">全部定时任务</p>
              </CardContent>
            </Card>
            <Card className="bg-gradient-to-br from-green-500/10 to-green-500/5 border-green-500/20">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium text-green-700">运行中</CardTitle>
                <CheckCircle2 className="h-4 w-4 text-green-500" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{stats.enabledCount}</div>
                <p className="text-xs text-muted-foreground mt-1">正在运行的任务</p>
              </CardContent>
            </Card>
            <Card className="bg-gradient-to-br from-yellow-500/10 to-yellow-500/5 border-yellow-500/20">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium text-yellow-700">已暂停</CardTitle>
                <Pause className="h-4 w-4 text-yellow-500" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{stats.pausedCount}</div>
                <p className="text-xs text-muted-foreground mt-1">暂停执行的任务</p>
              </CardContent>
            </Card>
          </div>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>任务列表</CardTitle>
              <div className="flex items-center gap-2">
                <Button type="button" variant="outline" onClick={() => setCategoryDialogOpen(true)}><FolderKanban className="h-4 w-4 mr-2" />分类管理</Button>
                <Button type="button" onClick={() => { setEditJob(null); setEditDialogOpen(true); }}><Plus className="h-4 w-4 mr-2" />新建任务</Button>
              </div>
            </CardHeader>
            <CardContent>
              <PaginatedTable<ScheduleJobResponse, ScheduleJobQuery>
                ref={tableRef}
                fetchFn={getScheduleJobs}
                columns={columns}
                searchFields={searchFields}
                rowKey="id"
                minWidth="1600px"
              />
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="dashboard">
          <Dashboard />
        </TabsContent>
      </Tabs>

      {/* 弹窗 */}
      <CategoryManageDialog open={categoryDialogOpen} onOpenChange={setCategoryDialogOpen} onSuccess={loadCategories} />
      <JobLogDialog open={logDialogOpen} onOpenChange={setLogDialogOpen} job={selectedJob} />
      <JobEditDialog open={editDialogOpen} onOpenChange={setEditDialogOpen} job={editJob} categories={categories} onSuccess={() => tableRef.current?.refresh()} />
      <ConfirmDialog
        open={deleteDialogOpen}
        onOpenChange={setDeleteDialogOpen}
        title="确认删除定时任务"
        description="您确定要删除以下定时任务吗？此操作无法撤销。"
        item={deleteJob}
        onConfirm={async () => { if (deleteJob) await deleteScheduleJob(deleteJob.id); }}
        onSuccess={() => { toast({ title: '删除成功', description: `任务 "${deleteJob?.jobName}" 已删除` }); setDeleteJob(null); tableRef.current?.refresh(); }}
        variant="destructive"
        confirmText="确认删除"
      >
        {deleteJob && (
          <div className="rounded-md border p-3 space-y-2 bg-muted/50">
            <div className="flex items-center gap-2"><span className="text-sm font-medium text-muted-foreground">任务名称:</span><span className="font-medium">{deleteJob.jobName}</span></div>
            <div className="flex items-center gap-2"><span className="text-sm font-medium text-muted-foreground">Bean名称:</span><code className="text-xs bg-background px-2 py-1 rounded">{deleteJob.beanName}</code></div>
          </div>
        )}
      </ConfirmDialog>
    </div>
  );
};

export default ScheduleJobList;
