import React, { useState, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, CardHeader, CardTitle, CardContent, CardDescription } from '@/components/ui/card';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { DataTablePagination } from '@/components/ui/pagination';
import { FormRenderer } from '@/components/FormDesigner';
import { 
  Loader2, Plus, Search, Eye, Edit, FileText, Ban, Trash2, 
  Database, MoreHorizontal, CheckCircle2, XCircle, Clock, AlertCircle,
  Folder, Activity, Settings
} from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Separator } from '@/components/ui/separator';
import { getDefinitions, publishDefinition, disableDefinition, deleteDefinition } from './service';
import { getEnabledCategories } from '../Category/service';
import type { FormDefinitionResponse, FormDefinitionStatus } from './types';
import type { FormCategoryResponse } from '../Category/types';
import type { Page } from '@/types/base';
import { DEFAULT_PAGE_SIZE, DEFAULT_CURRENT } from '@/utils/page';
import CreateModal from './components/CreateModal';
import EditBasicInfoModal from './components/EditBasicInfoModal';

/**
 * 表单定义列表页
 */
const FormDefinitionList: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<Page<FormDefinitionResponse> | null>(null);
  const [categories, setCategories] = useState<FormCategoryResponse[]>([]);
  const [query, setQuery] = useState({
    pageNum: DEFAULT_CURRENT - 1,
    pageSize: DEFAULT_PAGE_SIZE,
    name: '',
    categoryId: undefined as number | undefined,
    status: undefined as FormDefinitionStatus | undefined,
  });

  // 创建表单弹窗
  const [createModalVisible, setCreateModalVisible] = useState(false);

  // 编辑基本信息弹窗
  const [editBasicInfoVisible, setEditBasicInfoVisible] = useState(false);
  const [editBasicInfoRecord, setEditBasicInfoRecord] = useState<FormDefinitionResponse | null>(null);

  // 预览弹窗
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewForm, setPreviewForm] = useState<FormDefinitionResponse | null>(null);

  // 删除确认弹窗
  const [deleteVisible, setDeleteVisible] = useState(false);
  const [deleteForm, setDeleteForm] = useState<FormDefinitionResponse | null>(null);
  const [deleting, setDeleting] = useState(false);

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

  // 加载数据
  const loadData = async () => {
    setLoading(true);
    try {
      const result = await getDefinitions(query);
      setData(result);
    } catch (error) {
      console.error('加载表单定义失败:', error);
    } finally {
      setLoading(false);
    }
  };

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

  useEffect(() => {
    loadData();
  }, [query]);

  // 统计数据
  const stats = useMemo(() => {
    const total = data?.totalElements || 0;
    const draftCount = data?.content?.filter(item => item.status === 'DRAFT').length || 0;
    const publishedCount = data?.content?.filter(item => item.status === 'PUBLISHED').length || 0;
    const disabledCount = data?.content?.filter(item => item.status === 'DISABLED').length || 0;
    
    return { total, draftCount, publishedCount, disabledCount };
  }, [data]);

  // 搜索
  const handleSearch = () => {
    setQuery(prev => ({
      ...prev,
      pageNum: 0,
    }));
  };

  // 重置搜索
  const handleReset = () => {
    setQuery({
      pageNum: 0,
      pageSize: DEFAULT_PAGE_SIZE,
      name: '',
      categoryId: undefined,
      status: undefined,
    });
  };

  // 创建表单
  const handleCreate = () => {
    setCreateModalVisible(true);
  };

  // 编辑表单设计
  const handleEdit = (record: FormDefinitionResponse) => {
    navigate(`/form/definitions/${record.id}/design`);
  };

  // 编辑基本信息
  const handleEditBasicInfo = (record: FormDefinitionResponse) => {
    setEditBasicInfoRecord(record);
    setEditBasicInfoVisible(true);
  };

  // 预览表单
  const handlePreview = (record: FormDefinitionResponse) => {
    setPreviewForm(record);
    setPreviewVisible(true);
  };

  // 发布表单
  const handlePublish = async (record: FormDefinitionResponse) => {
    try {
      await publishDefinition(record.id);
      loadData();
    } catch (error) {
      console.error('发布表单失败:', error);
    }
  };

  // 禁用表单
  const handleDisable = async (record: FormDefinitionResponse) => {
    try {
      await disableDefinition(record.id);
      loadData();
    } catch (error) {
      console.error('禁用表单失败:', error);
    }
  };

  // 打开删除确认弹窗
  const handleDeleteClick = (record: FormDefinitionResponse) => {
    setDeleteForm(record);
    setDeleteVisible(true);
  };

  // 确认删除
  const handleDeleteConfirm = async () => {
    if (!deleteForm) return;
    setDeleting(true);
    try {
      await deleteDefinition(deleteForm.id);
      setDeleteVisible(false);
      setDeleteForm(null);
      loadData();
    } catch (error) {
      console.error('删除表单失败:', error);
    } finally {
      setDeleting(false);
    }
  };

  // 查看数据
  const handleViewData = (record: FormDefinitionResponse) => {
    navigate(`/form/data?formDefinitionId=${record.id}`);
  };

  // 根据分类 ID 获取分类信息
  const getCategoryInfo = (categoryId?: number) => {
    return categories.find(cat => cat.id === categoryId);
  };

  // 状态徽章（带图标）
  const getStatusBadge = (status: FormDefinitionStatus) => {
    const statusMap: Record<FormDefinitionStatus, { 
      variant: 'default' | 'secondary' | 'destructive' | 'success' | 'outline'; 
      text: string;
      icon: React.ReactNode;
    }> = {
      DRAFT: { 
        variant: 'outline', 
        text: '草稿',
        icon: <Clock className="h-3 w-3 mr-1" />
      },
      PUBLISHED: { 
        variant: 'success', 
        text: '已发布',
        icon: <CheckCircle2 className="h-3 w-3 mr-1" />
      },
      DISABLED: { 
        variant: 'secondary', 
        text: '已禁用',
        icon: <XCircle className="h-3 w-3 mr-1" />
      },
    };
    const statusInfo = statusMap[status];
    return (
      <Badge variant={statusInfo.variant} className="flex items-center w-fit">
        {statusInfo.icon}
        {statusInfo.text}
      </Badge>
    );
  };

  const pageCount = data?.totalElements ? Math.ceil(data.totalElements / query.pageSize) : 0;

  return (
    <div className="flex flex-col gap-6 p-6">
      {/* 统计卡片 */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总表单数</CardTitle>
            <Activity className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</div>
            <p className="text-xs text-muted-foreground mt-1">
              全部表单定义
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">草稿</CardTitle>
            <Clock className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.draftCount}</div>
            <p className="text-xs text-muted-foreground mt-1">
              待发布的表单
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">已发布</CardTitle>
            <CheckCircle2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.publishedCount}</div>
            <p className="text-xs text-muted-foreground mt-1">
              正在使用的表单
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">已禁用</CardTitle>
            <XCircle className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.disabledCount}</div>
            <p className="text-xs text-muted-foreground mt-1">
              已停用的表单
            </p>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>表单定义管理</CardTitle>
              <CardDescription className="mt-2">
                创建和管理表单定义，支持版本控制和发布管理
              </CardDescription>
            </div>
            <Button onClick={handleCreate} size="default">
              <Plus className="h-4 w-4 mr-2" />
              创建表单
            </Button>
          </div>
        </CardHeader>
        <Separator />
        <CardContent className="pt-6">
          {/* 搜索栏 */}
          <div className="flex items-center gap-4 mb-6">
            <div className="flex-1 max-w-md">
              <Input
                placeholder="搜索表单名称或标识..."
                value={query.name}
                onChange={(e) => setQuery(prev => ({ ...prev, name: e.target.value }))}
                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                className="h-9"
              />
            </div>
            <Select
              value={query.categoryId?.toString() || undefined}
              onValueChange={(value) => setQuery(prev => ({ ...prev, categoryId: Number(value) }))}
            >
              <SelectTrigger className="w-[160px] h-9">
                <SelectValue placeholder="全部分类" />
              </SelectTrigger>
              <SelectContent>
                {categories.map(cat => (
                  <SelectItem key={cat.id} value={cat.id.toString()}>
                    <div className="flex items-center gap-2">
                      {cat.icon && <Folder className="h-3.5 w-3.5" />}
                      {cat.name}
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select
              value={query.status || undefined}
              onValueChange={(value) => setQuery(prev => ({ ...prev, status: value as FormDefinitionStatus }))}
            >
              <SelectTrigger className="w-[140px] h-9">
                <SelectValue placeholder="全部状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="DRAFT">草稿</SelectItem>
                <SelectItem value="PUBLISHED">已发布</SelectItem>
                <SelectItem value="DISABLED">已禁用</SelectItem>
              </SelectContent>
            </Select>
            <Button onClick={handleSearch} size="sm">
              <Search className="h-4 w-4 mr-2" />
              搜索
            </Button>
            <Button variant="outline" onClick={handleReset} size="sm">
              重置
            </Button>
          </div>

          {/* 表格 */}
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[250px]">表单名称</TableHead>
                  <TableHead className="w-[200px]">表单标识</TableHead>
                  <TableHead className="w-[150px]">分类</TableHead>
                  <TableHead className="w-[80px]">版本</TableHead>
                  <TableHead className="w-[120px]">状态</TableHead>
                  <TableHead className="w-[180px]">更新时间</TableHead>
                  <TableHead className="w-[100px] text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={7} className="h-32 text-center">
                      <div className="flex items-center justify-center">
                        <Loader2 className="h-6 w-6 animate-spin mr-2" />
                        <span className="text-sm text-muted-foreground">加载中...</span>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : data?.content && data.content.length > 0 ? (
                  data.content.map((record) => {
                    const categoryInfo = getCategoryInfo(record.categoryId);
                    return (
                      <TableRow key={record.id} className="hover:bg-muted/50">
                        <TableCell>
                          <div>
                            <div className="font-medium">{record.name}</div>
                            {record.description && (
                              <div className="text-xs text-muted-foreground mt-1 line-clamp-1">
                                {record.description}
                              </div>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          <code className="text-xs bg-muted px-2 py-1 rounded">{record.key}</code>
                        </TableCell>
                        <TableCell>
                          {categoryInfo ? (
                            <div className="flex items-center gap-2">
                              <Folder className="h-4 w-4 text-muted-foreground" />
                              <span className="text-sm">{categoryInfo.name}</span>
                            </div>
                          ) : (
                            <span className="text-sm text-muted-foreground">-</span>
                          )}
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline" className="font-mono">
                            v{record.formVersion}
                          </Badge>
                        </TableCell>
                        <TableCell>{getStatusBadge(record.status)}</TableCell>
                        <TableCell className="text-sm text-muted-foreground">
                          {record.updateTime || record.createTime}
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center justify-end gap-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handlePreview(record)}
                              className="h-8 w-8 p-0"
                            >
                              <Eye className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleEdit(record)}
                              className="h-8 w-8 p-0"
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <DropdownMenu>
                              <DropdownMenuTrigger asChild>
                                <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                                  <MoreHorizontal className="h-4 w-4" />
                                </Button>
                              </DropdownMenuTrigger>
                              <DropdownMenuContent align="end" className="w-[160px]">
                                <DropdownMenuItem onClick={() => handleEditBasicInfo(record)}>
                                  <Settings className="h-4 w-4 mr-2" />
                                  编辑基本信息
                                </DropdownMenuItem>
                                <DropdownMenuItem onClick={() => handleViewData(record)}>
                                  <Database className="h-4 w-4 mr-2" />
                                  查看数据
                                </DropdownMenuItem>
                                <DropdownMenuSeparator />
                                {record.status === 'DRAFT' && (
                                  <DropdownMenuItem onClick={() => handlePublish(record)}>
                                    <FileText className="h-4 w-4 mr-2" />
                                    发布表单
                                  </DropdownMenuItem>
                                )}
                                {record.status === 'PUBLISHED' && (
                                  <DropdownMenuItem onClick={() => handleDisable(record)}>
                                    <Ban className="h-4 w-4 mr-2" />
                                    禁用表单
                                  </DropdownMenuItem>
                                )}
                                <DropdownMenuSeparator />
                                <DropdownMenuItem
                                  onClick={() => handleDeleteClick(record)}
                                  className="text-destructive focus:text-destructive"
                                >
                                  <Trash2 className="h-4 w-4 mr-2" />
                                  删除表单
                                </DropdownMenuItem>
                              </DropdownMenuContent>
                            </DropdownMenu>
                          </div>
                        </TableCell>
                      </TableRow>
                    );
                  })
                ) : (
                  <TableRow>
                    <TableCell colSpan={7} className="h-32 text-center">
                      <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                        <FileText className="w-12 h-12 mb-4 opacity-20" />
                        <div className="text-sm font-medium">暂无表单定义</div>
                        <div className="text-xs mt-1">点击右上角"创建表单"开始</div>
                      </div>
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>

          {/* 分页 */}
          {pageCount > 1 && (
            <div className="mt-4">
              <DataTablePagination
                pageIndex={query.pageNum + 1}
                pageSize={query.pageSize}
                pageCount={pageCount}
                onPageChange={(page) => setQuery(prev => ({
                  ...prev,
                  pageNum: page - 1
                }))}
              />
            </div>
          )}
        </CardContent>
      </Card>

      {/* 预览弹窗 */}
      {previewForm && (
        <Dialog open={previewVisible} onOpenChange={setPreviewVisible}>
          <DialogContent className="max-w-4xl max-h-[85vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>预览表单</DialogTitle>
              <DialogDescription>
                {previewForm.name} - {previewForm.key} (v{previewForm.formVersion})
              </DialogDescription>
            </DialogHeader>
            <Separator className="my-4" />
            <div className="py-4">
              <FormRenderer
                schema={previewForm.schema}
                value={{}}
                readonly={true}
                showSubmit={false}
                onCancel={() => setPreviewVisible(false)}
              />
            </div>
          </DialogContent>
        </Dialog>
      )}

      {/* 删除确认弹窗 */}
      {deleteForm && (
        <Dialog open={deleteVisible} onOpenChange={setDeleteVisible}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <AlertCircle className="h-5 w-5 text-destructive" />
                确认删除
              </DialogTitle>
              <DialogDescription>
                此操作不可撤销，确定要删除表单吗？
              </DialogDescription>
            </DialogHeader>
            <div className="py-4">
              <div className="rounded-lg bg-muted p-4 space-y-2">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">表单名称：</span>
                  <span className="text-sm font-medium">{deleteForm.name}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">表单标识：</span>
                  <code className="text-xs bg-background px-2 py-1 rounded">{deleteForm.key}</code>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">版本：</span>
                  <span className="text-sm">v{deleteForm.formVersion}</span>
                </div>
              </div>
            </div>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => setDeleteVisible(false)}
                disabled={deleting}
              >
                取消
              </Button>
              <Button
                variant="destructive"
                onClick={handleDeleteConfirm}
                disabled={deleting}
              >
                {deleting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                确认删除
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}

      {/* 创建表单弹窗 */}
      <CreateModal
        visible={createModalVisible}
        onClose={() => setCreateModalVisible(false)}
        onSuccess={() => {
          setCreateModalVisible(false);
          loadData();
        }}
      />

      {/* 编辑基本信息弹窗 */}
      <EditBasicInfoModal
        visible={editBasicInfoVisible}
        record={editBasicInfoRecord}
        onClose={() => {
          setEditBasicInfoVisible(false);
          setEditBasicInfoRecord(null);
        }}
        onSuccess={() => {
          loadData();
        }}
      />
    </div>
  );
};

export default FormDefinitionList;
