'use client';

import { useParams, useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api/apiClient';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import {
  ArrowLeft,
  Clock,
  User,
  FolderKanban,
  Cpu,
  CheckCircle2,
  XCircle,
  AlertCircle,
  Loader2,
  RotateCcw,
  Trash2,
  Calendar,
} from 'lucide-react';
import { format } from 'date-fns';
import { useRetryAdminTask, useDeleteAdminTask, adminTaskKeys } from '@/lib/hooks/admin/useAdminTasks';
import { useQueryClient } from '@tanstack/react-query';

interface TaskDetail {
  id: string;
  type: string;
  status: string;
  model: string;
  provider: string;
  projectId?: string;
  projectName?: string;
  userId?: string;
  userName?: string;
  userEmail?: string;
  createdAt: string;
  startedAt?: string;
  completedAt?: string;
  duration?: number;
  error?: string;
  retryCount: number;
  maxRetries: number;
}

interface ApiResponse<T> {
  code?: string;
  message?: string;
  data?: T;
}

async function fetchTaskDetail(taskId: string): Promise<TaskDetail> {
  const response = await api.get<ApiResponse<TaskDetail>>(`/api/v1/admin/tasks/${taskId}`);
  const data = response.data?.data ?? response.data;
  if (!data || typeof data !== 'object') {
    throw new Error('Invalid task detail response');
  }
  return data as TaskDetail;
}

const statusConfig: Record<string, { label: string; variant: 'default' | 'secondary' | 'destructive' | 'outline' }> = {
  pending: { label: '等待中', variant: 'secondary' },
  processing: { label: '处理中', variant: 'default' },
  success: { label: '成功', variant: 'default' },
  succeeded: { label: '成功', variant: 'default' },
  completed: { label: '已完成', variant: 'default' },
  failed: { label: '失败', variant: 'destructive' },
  timeout: { label: '超时', variant: 'destructive' },
  retrying: { label: '重试中', variant: 'outline' },
};

const typeLabels: Record<string, string> = {
  image: '图像生成',
  video: '视频生成',
  audio: '音频生成',
  music: '音乐生成',
  script: '脚本处理',
  other: '其他',
};

export default function AdminTaskDetailPage() {
  const params = useParams();
  const router = useRouter();
  const taskId = params.id as string;
  const queryClient = useQueryClient();
  const retryMutation = useRetryAdminTask();
  const deleteMutation = useDeleteAdminTask();

  const { data: task, isLoading, error } = useQuery({
    queryKey: adminTaskKeys.detail(taskId),
    queryFn: () => fetchTaskDetail(taskId),
    enabled: !!taskId,
    staleTime: 5 * 1000,
    refetchInterval: (query) => {
      const task = query.state.data;
      return (task?.status === 'pending' || task?.status === 'processing') ? 10000 : false;
    },
  });

  const handleRetry = () => {
    retryMutation.mutate(taskId, {
      onSuccess: () => {
        queryClient.invalidateQueries({ queryKey: adminTaskKeys.detail(taskId) });
      },
    });
  };

  const handleDelete = () => {
    if (confirm('确定要删除此任务吗？')) {
      deleteMutation.mutate(taskId, {
        onSuccess: () => {
          router.push('/admin/tasks');
        },
      });
    }
  };

  const formatDuration = (seconds?: number) => {
    if (!seconds) return '-';
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    if (mins > 0) {
      return `${mins}分${secs}秒`;
    }
    return `${secs}秒`;
  };

  const formatDateTime = (dateString?: string) => {
    if (!dateString) return '-';
    try {
      return format(new Date(dateString), 'yyyy-MM-dd HH:mm:ss');
    } catch {
      return dateString;
    }
  };

  if (isLoading) {
    return (
      <div className="container mx-auto p-6 space-y-6">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon">
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <Skeleton className="h-8 w-48" />
            <Skeleton className="h-4 w-32 mt-2" />
          </div>
        </div>
        <Card>
          <CardHeader>
            <Skeleton className="h-6 w-32" />
          </CardHeader>
          <CardContent className="space-y-4">
            {Array.from({ length: 6 }).map((_, i) => (
              <div key={i} className="flex items-center gap-4">
                <Skeleton className="h-4 w-24" />
                <Skeleton className="h-4 w-48" />
              </div>
            ))}
          </CardContent>
        </Card>
      </div>
    );
  }

  if (error || !task) {
    return (
      <div className="container mx-auto p-6 space-y-6">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" onClick={() => router.push('/admin/tasks')}>
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold">任务详情</h1>
          </div>
        </div>
        <Card>
          <CardContent className="py-8">
            <div className="text-center">
              <AlertCircle className="h-12 w-12 mx-auto text-destructive mb-4" />
              <h3 className="text-lg font-semibold mb-2">任务不存在或加载失败</h3>
              <p className="text-muted-foreground mb-4">
                {error instanceof Error ? error.message : '无法获取任务信息'}
              </p>
              <Button onClick={() => router.push('/admin/tasks')}>
                返回任务列表
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  const statusInfo = statusConfig[task.status] || { label: task.status, variant: 'secondary' };
  const typeLabel = typeLabels[task.type] || task.type;

  return (
    <div className="container mx-auto p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" onClick={() => router.push('/admin/tasks')}>
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold">任务详情</h1>
            <p className="text-muted-foreground text-sm mt-1">
              ID: {task.id.slice(0, 36)}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Badge variant={statusInfo.variant} className="text-sm">
            {statusInfo.label}
          </Badge>
          {(task.status === 'failed' || task.status === 'timeout') && (
            <Button
              variant="outline"
              size="sm"
              onClick={handleRetry}
              disabled={retryMutation.isPending}
            >
              <RotateCcw className="h-4 w-4 mr-2" />
              重试
            </Button>
          )}
          <Button
            variant="outline"
            size="sm"
            onClick={handleDelete}
            disabled={deleteMutation.isPending}
          >
            <Trash2 className="h-4 w-4 mr-2" />
            删除
          </Button>
        </div>
      </div>

      {/* Main Info Card */}
      <Card>
        <CardHeader>
          <CardTitle>基本信息</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="flex items-start gap-3">
              <div className="p-2 rounded-md bg-blue-500/10">
                <Cpu className="h-4 w-4 text-blue-500" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">任务类型</p>
                <p className="font-medium">{typeLabel}</p>
              </div>
            </div>

            <div className="flex items-start gap-3">
              <div className="p-2 rounded-md bg-purple-500/10">
                <Cpu className="h-4 w-4 text-purple-500" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">模型</p>
                <p className="font-medium">{task.model || '-'}</p>
                {task.provider && (
                  <p className="text-xs text-muted-foreground mt-1">{task.provider}</p>
                )}
              </div>
            </div>

            <div className="flex items-start gap-3">
              <div className="p-2 rounded-md bg-emerald-500/10">
                <User className="h-4 w-4 text-emerald-500" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">用户</p>
                {task.userName ? (
                  <>
                    <p className="font-medium">{task.userName}</p>
                    {task.userEmail && (
                      <p className="text-xs text-muted-foreground mt-1">{task.userEmail}</p>
                    )}
                  </>
                ) : (
                  <p className="font-medium text-muted-foreground">未知用户</p>
                )}
              </div>
            </div>

            <div className="flex items-start gap-3">
              <div className="p-2 rounded-md bg-amber-500/10">
                <FolderKanban className="h-4 w-4 text-amber-500" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">项目</p>
                {task.projectId ? (
                  <>
                    <p className="font-medium">{task.projectName || task.projectId.slice(0, 8)}</p>
                    <p className="text-xs text-muted-foreground mt-1">ID: {task.projectId.slice(0, 36)}</p>
                  </>
                ) : (
                  <p className="font-medium text-muted-foreground">-</p>
                )}
              </div>
            </div>

            <div className="flex items-start gap-3">
              <div className="p-2 rounded-md bg-cyan-500/10">
                <Clock className="h-4 w-4 text-cyan-500" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">处理时长</p>
                <p className="font-medium">{formatDuration(task.duration)}</p>
              </div>
            </div>

            <div className="flex items-start gap-3">
              <div className="p-2 rounded-md bg-rose-500/10">
                <RotateCcw className="h-4 w-4 text-rose-500" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">重试次数</p>
                <p className="font-medium">{task.retryCount} / {task.maxRetries}</p>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Time Info Card */}
      <Card>
        <CardHeader>
          <CardTitle>时间信息</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-3 gap-4">
            <div>
              <p className="text-sm text-muted-foreground mb-1">创建时间</p>
              <div className="flex items-center gap-2">
                <Calendar className="h-4 w-4 text-muted-foreground" />
                <p className="font-medium">{formatDateTime(task.createdAt)}</p>
              </div>
            </div>

            <div>
              <p className="text-sm text-muted-foreground mb-1">开始时间</p>
              <div className="flex items-center gap-2">
                <Clock className="h-4 w-4 text-muted-foreground" />
                <p className="font-medium">{formatDateTime(task.startedAt)}</p>
              </div>
            </div>

            <div>
              <p className="text-sm text-muted-foreground mb-1">完成时间</p>
              <div className="flex items-center gap-2">
                {task.status === 'success' || task.status === 'succeeded' || task.status === 'completed' ? (
                  <CheckCircle2 className="h-4 w-4 text-green-500" />
                ) : task.status === 'failed' || task.status === 'timeout' ? (
                  <XCircle className="h-4 w-4 text-red-500" />
                ) : (
                  <Loader2 className="h-4 w-4 text-blue-500 animate-spin" />
                )}
                <p className="font-medium">{formatDateTime(task.completedAt)}</p>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Error Info Card */}
      {task.error && (
        <Card className="border-destructive/50">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-destructive">
              <XCircle className="h-5 w-5" />
              错误信息
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm text-muted-foreground bg-destructive/10 p-4 rounded-md">
              {task.error}
            </p>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
