import React, { useState, useEffect } from 'react';
import { PageContainer } from '@/components/ui/page-container';
import { getProjectGroupPage } from './service';
import type { ProjectGroup, ProjectGroupQueryParams } from './types';
import { ProjectGroupTypeEnum } from './types';
import { getProjectTypeInfo } from './utils';
import ProjectGroupModal from './components/ProjectGroupModal';
import DeleteDialog from './components/DeleteDialog';
import {
  Table,
  TableHeader,
  TableBody,
  TableHead,
  TableRow,
  TableCell,
} from '@/components/ui/table';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/components/ui/use-toast';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { searchFormSchema, type SearchFormValues } from './schema';
import { DataTablePagination } from '@/components/ui/pagination';
import { Plus, Edit, Trash2, FolderKanban, Activity, Database, Layers, Boxes } from 'lucide-react';

const DEFAULT_PAGE_SIZE = 10;

const ProjectGroupList: React.FC = () => {
  const [modalVisible, setModalVisible] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [currentProject, setCurrentProject] = useState<ProjectGroup>();
  const [list, setList] = useState<ProjectGroup[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    pageNum: 1,
    pageSize: DEFAULT_PAGE_SIZE,
    totalElements: 0,
  });
  const [stats, setStats] = useState({ total: 0, enabled: 0, disabled: 0 });
  const { toast } = useToast();

  const form = useForm<SearchFormValues>({
    resolver: zodResolver(searchFormSchema),
    defaultValues: {
      projectGroupCode: '',
      projectGroupName: '',
      type: undefined,
      enabled: undefined,
    },
  });

  const loadData = async (params?: SearchFormValues) => {
    setLoading(true);
    try {
      const queryParams: ProjectGroupQueryParams = {
        ...params,
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize,
      };
      const data = await getProjectGroupPage(queryParams);
      setList(data.content || []);
      setPagination((prev) => ({
        ...prev,
        totalElements: data.totalElements,
      }));
      // 计算统计数据
      const all = data.content || [];
      setStats({
        total: all.length,
        enabled: all.filter((item) => item.enabled).length,
        disabled: all.filter((item) => !item.enabled).length,
      });
    } catch (error) {
      toast({
        variant: 'destructive',
        title: '加载失败',
        description: '加载数据失败，请稍后重试',
        duration: 3000,
      });
    } finally {
      setLoading(false);
    }
  };

  const handlePageChange = (page: number) => {
    setPagination((prev) => ({
      ...prev,
      pageNum: page,
    }));
  };

  useEffect(() => {
    loadData(form.getValues());
  }, [pagination.pageNum, pagination.pageSize]);

  const handleEdit = (project: ProjectGroup) => {
    setCurrentProject(project);
    setModalVisible(true);
  };

  const handleModalClose = () => {
    setModalVisible(false);
    setCurrentProject(undefined);
  };

  const handleSuccess = () => {
    setModalVisible(false);
    setCurrentProject(undefined);
    loadData(form.getValues());
  };

  return (
    <PageContainer>
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <h2 className="text-3xl font-bold tracking-tight">项目组管理</h2>
        <Button onClick={() => {
          setCurrentProject(undefined);
          setModalVisible(true);
        }}>
          <Plus className="h-4 w-4 mr-2" />
          新建项目组
        </Button>
      </div>

      {/* 统计卡片 */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总项目组数</CardTitle>
            <FolderKanban 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">所有项目组</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>
            <Activity className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{stats.enabled}</div>
            <p className="text-xs text-muted-foreground">正在使用中</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>
            <Database className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-gray-600">{stats.disabled}</div>
            <p className="text-xs text-muted-foreground">暂时停用</p>
          </CardContent>
        </Card>
      </div>

      {/* 搜索过滤 */}
      <Card>
        <div className="p-6">
          <div className="flex items-center gap-4">
            <Input
              placeholder="项目组编码"
              value={form.watch('projectGroupCode')}
              onChange={(e) => form.setValue('projectGroupCode', e.target.value)}
              className="max-w-[200px]"
            />
            <Input
              placeholder="项目组名称"
              value={form.watch('projectGroupName')}
              onChange={(e) => form.setValue('projectGroupName', e.target.value)}
              className="max-w-[200px]"
            />
            <Select
              value={form.watch('type')}
              onValueChange={(value) => form.setValue('type', value as ProjectGroupTypeEnum)}
            >
              <SelectTrigger className="max-w-[200px]">
                <SelectValue placeholder="项目组类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={ProjectGroupTypeEnum.PRODUCT}>产品型</SelectItem>
                <SelectItem value={ProjectGroupTypeEnum.PROJECT}>项目型</SelectItem>
              </SelectContent>
            </Select>
            <Select
              value={form.watch('enabled')?.toString()}
              onValueChange={(value) => form.setValue('enabled', value === 'true')}
            >
              <SelectTrigger className="max-w-[200px]">
                <SelectValue placeholder="状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="true">启用</SelectItem>
                <SelectItem value="false">禁用</SelectItem>
              </SelectContent>
            </Select>
            <Button variant="outline" onClick={() => form.reset()}>
              重置
            </Button>
            <Button onClick={() => loadData(form.getValues())}>搜索</Button>
          </div>
        </div>
      </Card>

      {/* 数据表格 */}
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>项目组列表</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[140px]">项目组编码</TableHead>
                  <TableHead className="w-[140px]">项目组名称</TableHead>
                  <TableHead className="w-[200px]">项目组描述</TableHead>
                  <TableHead className="w-[120px]">项目组类型</TableHead>
                  <TableHead className="w-[100px]">环境数量</TableHead>
                  <TableHead className="w-[100px]">项目数量</TableHead>
                  <TableHead className="w-[80px]">状态</TableHead>
                  <TableHead className="w-[80px]">排序</TableHead>
                  <TableHead className="w-[180px]">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {list.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={9} className="h-24 text-center">
                      暂无数据
                    </TableCell>
                  </TableRow>
                ) : (
                  list.map((item) => {
                    const typeInfo = getProjectTypeInfo(item.type);
                    return (
                      <TableRow key={item.id}>
                        <TableCell className="font-medium">{item.projectGroupCode}</TableCell>
                        <TableCell>{item.projectGroupName}</TableCell>
                        <TableCell className="text-muted-foreground">
                          {item.projectGroupDesc}
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline" className="inline-flex items-center gap-1">
                            {typeInfo.icon}
                            {typeInfo.label}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-1">
                            <Layers className="h-3 w-3 text-muted-foreground" />
                            <span>{item.totalEnvironments}</span>
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-1">
                            <Boxes className="h-3 w-3 text-muted-foreground" />
                            <span>{item.totalApplications}</span>
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge
                            variant={item.enabled ? 'default' : 'secondary'}
                            className="inline-flex"
                          >
                            {item.enabled ? '启用' : '禁用'}
                          </Badge>
                        </TableCell>
                        <TableCell>{item.sort}</TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleEdit(item)}
                            >
                              <Edit className="h-4 w-4 mr-1" />
                              编辑
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => {
                                setCurrentProject(item);
                                setDeleteDialogOpen(true);
                              }}
                              className="text-destructive hover:text-destructive"
                            >
                              <Trash2 className="h-4 w-4 mr-1" />
                              删除
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    );
                  })
                )}
              </TableBody>
            </Table>
            <div className="flex justify-end border-t border-border bg-muted/40">
              <DataTablePagination
                pageIndex={pagination.pageNum}
                pageSize={pagination.pageSize}
                pageCount={Math.ceil(pagination.totalElements / pagination.pageSize)}
                onPageChange={handlePageChange}
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 对话框 */}
      <ProjectGroupModal
        open={modalVisible}
        onCancel={handleModalClose}
        onSuccess={handleSuccess}
        initialValues={currentProject}
      />
      <DeleteDialog
        open={deleteDialogOpen}
        record={currentProject}
        onOpenChange={setDeleteDialogOpen}
        onSuccess={handleSuccess}
      />
    </PageContainer>
  );
};

export default ProjectGroupList;
