import React, {useState, useEffect} from 'react';
import {PageContainer} from '@/components/ui/page-container';
import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    TeamOutlined,
    EnvironmentOutlined,
    SearchOutlined,
} from '@ant-design/icons';
import {getProjectGroupPage, deleteProjectGroup} from './service';
import type {ProjectGroup, ProjectGroupQueryParams} from './types';
import {ProjectGroupTypeEnum} from './types';
import {getProjectTypeInfo} from './utils';
import ProjectGroupModal from './components/ProjectGroupModal';
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 {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
} from "@/components/ui/form";
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 {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import {useForm} from "react-hook-form";
import {zodResolver} from "@hookform/resolvers/zod";
import {searchFormSchema, type SearchFormValues} from "./schema";
import {DataTablePagination} from "@/components/ui/pagination";

interface Column {
    accessorKey?: keyof ProjectGroup;
    id?: string;
    header: string;
    size: number;
    cell?: (props: { row: { original: ProjectGroup } }) => React.ReactNode;
}

const ProjectGroupList: React.FC = () => {
    const [modalVisible, setModalVisible] = useState(false);
    const [currentProject, setCurrentProject] = useState<ProjectGroup>();
    const [list, setList] = useState<ProjectGroup[]>([]);
    const [loading, setLoading] = useState(false);
    const [deleteDialogOpen, setDeleteDialogOpen] = useState<Record<string | number, boolean>>({});
    const [pagination, setPagination] = useState({
        pageNum: 1,
        pageSize: 10,
        totalElements: 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,
            }));
        } 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 handleDelete = async (id: number) => {
        try {
            await deleteProjectGroup(id);
            toast({
                variant: "default",
                title: "操作成功",
                description: "项目组删除成功",
                duration: 3000,
            });
            loadData(form.getValues());
            setDeleteDialogOpen(prev => ({...prev, [id]: false}));
        } catch (error) {
            toast({
                variant: "destructive",
                title: "操作失败",
                description: "删除项目组失败，请稍后重试",
                duration: 3000,
            });
        }
    };

    const openDeleteDialog = (id: number) => {
        setDeleteDialogOpen(prev => ({...prev, [id]: true}));
    };

    const closeDeleteDialog = (id: number) => {
        setDeleteDialogOpen(prev => ({...prev, [id]: false}));
    };

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

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

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

    const handleSearch = async (values: SearchFormValues) => {
        loadData(values);
    };

    const columns: Column[] = [
        {
            accessorKey: 'projectGroupCode',
            header: '项目组编码',
            size: 180,
        },
        {
            accessorKey: 'projectGroupName',
            header: '项目组名称',
            size: 150,
        },
        {
            accessorKey: 'projectGroupDesc',
            header: '项目组描述',
            size: 200,
        },
        {
            id: 'type',
            header: '项目组类型',
            size: 120,
            cell: ({row}) => {
                const typeInfo = getProjectTypeInfo(row.original.type);
                return (
                    <Badge variant="outline" className="flex items-center gap-1">
                        {typeInfo.icon}
                        {typeInfo.label}
                    </Badge>
                );
            },
        },
        {
            accessorKey: 'totalEnvironments',
            header: '环境数量',
            size: 100,
            cell: ({row}) => (
                <div className="flex items-center gap-1">
                    <EnvironmentOutlined/>
                    <span>{row.original.totalEnvironments}</span>
                </div>
            ),
        },
        {
            accessorKey: 'totalApplications',
            header: '项目数量',
            size: 100,
            cell: ({row}) => (
                <div className="flex items-center gap-1">
                    <TeamOutlined/>
                    <span>{row.original.totalApplications}</span>
                </div>
            ),
        },
        {
            accessorKey: 'enabled',
            header: '状态',
            size: 100,
            cell: ({row}) => (
                <Badge variant={row.original.enabled ? "outline" : "secondary"}>
                    {row.original.enabled ? '启用' : '禁用'}
                </Badge>
            ),
        },
        {
            accessorKey: 'sort',
            header: '排序',
            size: 80,
        },
        {
            id: 'actions',
            header: '操作',
            size: 180,
            cell: ({row}) => (
                <div className="flex items-center gap-2">
                    <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEdit(row.original)}
                    >
                        <EditOutlined className="mr-1"/>
                        编辑
                    </Button>
                    <AlertDialog 
                        open={deleteDialogOpen[row.original.id] || false}
                        onOpenChange={(open) => {
                            if (!open) closeDeleteDialog(row.original.id);
                        }}
                    >
                        <AlertDialogTrigger asChild>
                            <Button
                                variant="ghost"
                                size="sm"
                                className="text-destructive"
                                onClick={() => openDeleteDialog(row.original.id)}
                            >
                                <DeleteOutlined className="mr-1"/>
                                删除
                            </Button>
                        </AlertDialogTrigger>
                        <AlertDialogContent>
                            <AlertDialogHeader>
                                <AlertDialogTitle>确定要删除该项目组吗？</AlertDialogTitle>
                                <AlertDialogDescription>
                                    删除后将无法恢复，请谨慎操作
                                </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                                <AlertDialogCancel onClick={() => closeDeleteDialog(row.original.id)}>
                                    取消
                                </AlertDialogCancel>
                                <AlertDialogAction
                                    onClick={() => handleDelete(row.original.id)}
                                >
                                    确定
                                </AlertDialogAction>
                            </AlertDialogFooter>
                        </AlertDialogContent>
                    </AlertDialog>
                </div>
            ),
        },
    ];

    return (
        <PageContainer>
            <div className="flex items-center justify-between">
                <h2 className="text-3xl font-bold tracking-tight">项目组管理</h2>
                <Button onClick={() => setModalVisible(true)}>
                    <PlusOutlined className="mr-1"/>
                    新建
                </Button>
            </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 className="p-0">
                    <div className="relative rounded-md border">
                        <div className="overflow-auto">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead className="min-w-[140px]">项目组编码</TableHead>
                                        <TableHead className="min-w-[140px]">项目组名称</TableHead>
                                        <TableHead className="min-w-[200px]">项目组描述</TableHead>
                                        <TableHead className="min-w-[120px]">项目组类型</TableHead>
                                        <TableHead className="min-w-[100px]">环境数量</TableHead>
                                        <TableHead className="min-w-[100px]">项目数量</TableHead>
                                        <TableHead className="min-w-[80px]">状态</TableHead>
                                        <TableHead className="min-w-[80px]">排序</TableHead>
                                        <TableHead 
                                            className="sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.2)] min-w-[160px]"
                                        >
                                            操作
                                        </TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {list.map((item) => (
                                        <TableRow key={item.id}>
                                            <TableCell>{item.projectGroupCode}</TableCell>
                                            <TableCell>{item.projectGroupName}</TableCell>
                                            <TableCell>{item.projectGroupDesc}</TableCell>
                                            <TableCell>
                                                {(() => {
                                                    const typeInfo = getProjectTypeInfo(item.type);
                                                    return (
                                                        <Badge variant="outline" className="flex items-center gap-1">
                                                            {typeInfo.icon}
                                                            {typeInfo.label}
                                                        </Badge>
                                                    );
                                                })()}
                                            </TableCell>
                                            <TableCell>
                                                <div className="flex items-center gap-1">
                                                    <EnvironmentOutlined/>
                                                    <span>{item.totalEnvironments}</span>
                                                </div>
                                            </TableCell>
                                            <TableCell>
                                                <div className="flex items-center gap-1">
                                                    <TeamOutlined/>
                                                    <span>{item.totalApplications}</span>
                                                </div>
                                            </TableCell>
                                            <TableCell>
                                                <Badge variant={item.enabled ? "outline" : "secondary"}>
                                                    {item.enabled ? '启用' : '禁用'}
                                                </Badge>
                                            </TableCell>
                                            <TableCell>{item.sort}</TableCell>
                                            <TableCell className="sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.2)]">
                                                <div className="flex items-center gap-2">
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        onClick={() => handleEdit(item)}
                                                    >
                                                        <EditOutlined className="mr-1"/>
                                                        编辑
                                                    </Button>
                                                    <AlertDialog 
                                                        open={deleteDialogOpen[item.id] || false}
                                                        onOpenChange={(open) => {
                                                            if (!open) closeDeleteDialog(item.id);
                                                        }}
                                                    >
                                                        <AlertDialogTrigger asChild>
                                                            <Button
                                                                variant="ghost"
                                                                size="sm"
                                                                className="text-destructive"
                                                                onClick={() => openDeleteDialog(item.id)}
                                                            >
                                                                <DeleteOutlined className="mr-1"/>
                                                                删除
                                                            </Button>
                                                        </AlertDialogTrigger>
                                                        <AlertDialogContent>
                                                            <AlertDialogHeader>
                                                                <AlertDialogTitle>确定要删除该项目组吗？</AlertDialogTitle>
                                                                <AlertDialogDescription>
                                                                    删除后将无法恢复，请谨慎操作
                                                                </AlertDialogDescription>
                                                            </AlertDialogHeader>
                                                            <AlertDialogFooter>
                                                                <AlertDialogCancel onClick={() => closeDeleteDialog(item.id)}>
                                                                    取消
                                                                </AlertDialogCancel>
                                                                <AlertDialogAction
                                                                    onClick={() => handleDelete(item.id)}
                                                                >
                                                                    确定
                                                                </AlertDialogAction>
                                                            </AlertDialogFooter>
                                                        </AlertDialogContent>
                                                    </AlertDialog>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        </div>
                        <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}
            />
        </PageContainer>
    );
};

export default ProjectGroupList;
