import React, {useState} 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";

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 {toast} = useToast();

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

    const loadData = async (params?: ProjectGroupQueryParams) => {
        setLoading(true);
        try {
            const data = await getProjectGroupPage(params);
            setList(data.content);
        } catch (error) {
            toast({
                variant: "destructive",
                title: "加载失败",
                description: "加载数据失败，请稍后重试",
                duration: 3000,
            });
        } finally {
            setLoading(false);
        }
    };

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

    const handleDelete = async (id: number) => {
        try {
            await deleteProjectGroup(id);
            toast({
                variant: "default",
                title: "操作成功",
                description: "项目组删除成功",
                duration: 3000,
            });
            loadData(form.getValues());
        } catch (error) {
            toast({
                variant: "destructive",
                title: "操作失败",
                description: "删除项目组失败，请稍后重试",
                duration: 3000,
            });
        }
    };

    const handleAdd = () => {
        setCurrentProject(undefined);
        setModalVisible(true);
    };

    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: 120,
        },
        {
            accessorKey: 'projectGroupName',
            header: '项目组名称',
            size: 150,
        },
        {
            accessorKey: 'projectGroupDesc',
            header: '项目组描述',
            size: 200,
        },
        {
            accessorKey: 'type',
            header: '项目组类型',
            size: 150,
            cell: ({row}) => {
                const typeInfo = getProjectTypeInfo(row.original.type);
                return (
                    <Badge variant="outline">
                        <span className="flex items-center gap-1">
                            {typeInfo.icon}
                            {typeInfo.label}
                        </span>
                    </Badge>
                );
            },
        },
        {
            accessorKey: 'enabled',
            header: '状态',
            size: 100,
            cell: ({row}) => (
                <Badge variant={row.original.enabled ? "outline" : "secondary"}>
                    {row.original.enabled ? '启用' : '禁用'}
                </Badge>
            ),
        },
        {
            accessorKey: 'totalEnvironments',
            header: '环境数量',
            size: 100,
            cell: ({row}) => (
                <span className="flex items-center gap-1">
                    <EnvironmentOutlined/>
                    {row.original.totalEnvironments || 0}
                </span>
            ),
        },
        {
            accessorKey: 'totalApplications',
            header: '项目数量',
            size: 100,
            cell: ({row}) => (
                <span className="flex items-center gap-1">
                    <TeamOutlined/>
                    {row.original.totalApplications || 0}
                </span>
            ),
        },
        {
            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>
                        <AlertDialogTrigger asChild>
                            <Button
                                variant="ghost"
                                size="sm"
                                className="text-destructive"
                            >
                                <DeleteOutlined className="mr-1"/>
                                删除
                            </Button>
                        </AlertDialogTrigger>
                        <AlertDialogContent>
                            <AlertDialogHeader>
                                <AlertDialogTitle>确定要删除该项目组吗？</AlertDialogTitle>
                                <AlertDialogDescription>
                                    删除后将无法恢复，请谨慎操作
                                </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                                <AlertDialogCancel>取消</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.getValues('projectGroupCode')}
                            onChange={(e) => form.setValue('projectGroupCode', e.target.value)}
                            className="max-w-[200px]"
                        />
                        <Input
                            placeholder="项目组名称"
                            value={form.getValues('projectGroupName')}
                            onChange={(e) => form.setValue('projectGroupName', e.target.value)}
                            className="max-w-[200px]"
                        />
                        <Select
                            value={form.getValues('type')}
                            onValueChange={(value) => form.setValue('type', value)}
                        >
                            <SelectTrigger className="max-w-[200px]">
                                <SelectValue placeholder="项目组类型"/>
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value={ProjectGroupTypeEnum.PRODUCT}>产品型</SelectItem>
                                <SelectItem value={ProjectGroupTypeEnum.PROJECT}>项目型</SelectItem>
                            </SelectContent>
                        </Select>
                        <Select
                            value={form.getValues('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 variant="ghost" onClick={() => handleSearch(form.getValues())}>
                            <SearchOutlined className="mr-1"/>
                            搜索
                        </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>
                                    {columns.map((column) => (
                                        <TableHead
                                            key={column.accessorKey || column.id}
                                            style={{width: column.size}}
                                        >
                                            {column.header}
                                        </TableHead>
                                    ))}
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {list.map((item) => (
                                    <TableRow key={item.id}>
                                        {columns.map((column) => (
                                            <TableCell
                                                key={column.accessorKey || column.id}
                                            >
                                                {column.cell
                                                    ? column.cell({row: {original: item}})
                                                    : item[column.accessorKey!]}
                                            </TableCell>
                                        ))}
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </div>
                </CardContent>
            </Card>

            <ProjectGroupModal
                open={modalVisible}
                onCancel={handleModalClose}
                onSuccess={handleSuccess}
                initialValues={currentProject}
            />
        </PageContainer>
    );
};

export default ProjectGroupList;
