import React, { useEffect, useState } from 'react';
import type { TeamResponse } from '../types';
import { DevelopmentModeEnum, DEVELOPMENT_MODE_OPTIONS } from '../types';
import { createTeam, updateTeam } from '../service';
import { getUserList } from '@/pages/System/User/List/service';
import type { UserResponse } from '@/pages/System/User/List/types';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogBody,
    DialogTitle,
    DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectItemWithDescription,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { useToast } from "@/components/ui/use-toast";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { teamFormSchema, type TeamFormValues } from "../schema";
import { Textarea } from "@/components/ui/textarea";

interface TeamModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    onSuccess: () => void;
    initialValues?: TeamResponse;
}

const TeamModal: React.FC<TeamModalProps> = ({
    open,
    onOpenChange,
    onSuccess,
    initialValues,
}) => {
    const { toast } = useToast();
    const isEdit = !!initialValues?.id;
    const [users, setUsers] = useState<UserResponse[]>([]);

    const form = useForm<TeamFormValues>({
        resolver: zodResolver(teamFormSchema),
        defaultValues: {
            teamCode: "",
            teamName: "",
            description: "",
            ownerId: undefined,
            ownerName: "",
            enabled: true,
            sort: 0,
            developmentMode: DevelopmentModeEnum.STANDARD,
            enableGitSyncCheck: false,
        },
    });

    // 监听开发模式变化，自动调整Git同步检测选项
    const developmentMode = form.watch('developmentMode');
    useEffect(() => {
        const modeOption = DEVELOPMENT_MODE_OPTIONS.find(opt => opt.value === developmentMode);
        if (modeOption && !modeOption.enablesGitSyncCheck) {
            // 如果当前模式不支持Git同步检测，自动禁用
            form.setValue('enableGitSyncCheck', false);
        }
    }, [developmentMode, form]);

    // 加载用户列表
    const loadUsers = async () => {
        try {
            const response = await getUserList();
            if (response) {
                setUsers(response);
            }
        } catch (error) {
            console.error('加载用户列表失败:', error);
        }
    };

    useEffect(() => {
        if (open) {
            loadUsers();
            if (initialValues) {
                form.reset({
                    teamCode: initialValues.teamCode,
                    teamName: initialValues.teamName,
                    description: initialValues.description || "",
                    ownerId: initialValues.ownerId,
                    ownerName: initialValues.ownerName || "",
                    enabled: initialValues.enabled,
                    sort: initialValues.sort,
                    developmentMode: initialValues.developmentMode || DevelopmentModeEnum.STANDARD,
                    enableGitSyncCheck: initialValues.enableGitSyncCheck || false,
                });
            } else {
                form.reset({
                    teamCode: "",
                    teamName: "",
                    description: "",
                    ownerId: undefined,
                    ownerName: "",
                    enabled: true,
                    sort: 0,
                    developmentMode: DevelopmentModeEnum.STANDARD,
                    enableGitSyncCheck: false,
                });
            }
        }
    }, [open, initialValues, form]);

    const handleSubmit = async (values: TeamFormValues) => {
        try {
            if (isEdit) {
                await updateTeam(initialValues!.id, values as any);
                toast({
                    title: "更新成功",
                    description: `团队 "${values.teamName}" 已更新`,
                    duration: 3000,
                });
            } else {
                await createTeam(values as any);
                toast({
                    title: "创建成功",
                    description: `团队 "${values.teamName}" 已创建`,
                    duration: 3000,
                });
            }
            onSuccess();
            onOpenChange(false);
        } catch (error) {
            console.error(error);
            toast({
                variant: "destructive",
                title: isEdit ? "更新失败" : "创建失败",
                description: error instanceof Error ? error.message : "未知错误",
                duration: 3000,
            });
        }
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-[600px]">
                <DialogHeader>
                    <DialogTitle>{isEdit ? '编辑' : '新建'}团队</DialogTitle>
                </DialogHeader>
                <DialogBody>
                    <Form {...form}>
                        <form className="space-y-4">
                                <div className="grid grid-cols-2 gap-4">
                                    <FormField
                                        control={form.control}
                                        name="teamCode"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>团队编码</FormLabel>
                                                <FormControl>
                                                    <Input
                                                        disabled={isEdit}
                                                        placeholder="请输入团队编码"
                                                        {...field}
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    <FormField
                                        control={form.control}
                                        name="teamName"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>团队名称</FormLabel>
                                                <FormControl>
                                                    <Input placeholder="请输入团队名称" {...field} />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>

                                <FormField
                                    control={form.control}
                                    name="ownerId"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>团队负责人</FormLabel>
                                            <Select
                                                onValueChange={(value) => {
                                                    if (value === 'none') {
                                                        field.onChange(undefined);
                                                        form.setValue('ownerName', '');
                                                    } else {
                                                        const userId = Number(value);
                                                        const selectedUser = users.find(u => u.id === userId);
                                                        field.onChange(userId);
                                                        if (selectedUser) {
                                                            form.setValue('ownerName', selectedUser.nickname || selectedUser.username);
                                                        }
                                                    }
                                                }}
                                                value={field.value?.toString() || 'none'}
                                            >
                                                <FormControl>
                                                    <SelectTrigger>
                                                        <SelectValue placeholder="请选择负责人" />
                                                    </SelectTrigger>
                                                </FormControl>
                                                <SelectContent>
                                                    <SelectItem value="none">不选择负责人</SelectItem>
                                                    {users.map((user) => (
                                                        <SelectItem key={user.id} value={user.id.toString()}>
                                                            {user.nickname || user.username} ({user.username})
                                                        </SelectItem>
                                                    ))}
                                                </SelectContent>
                                            </Select>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <FormField
                                    control={form.control}
                                    name="description"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>团队描述</FormLabel>
                                            <FormControl>
                                                <Textarea
                                                    {...field}
                                                    placeholder="请输入团队描述"
                                                    rows={4}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <FormField
                                    control={form.control}
                                    name="developmentMode"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>开发模式</FormLabel>
                                            <Select
                                                onValueChange={field.onChange}
                                                value={field.value}
                                            >
                                                <FormControl>
                                                    <SelectTrigger>
                                                        <SelectValue placeholder="请选择开发模式" />
                                                    </SelectTrigger>
                                                </FormControl>
                                                <SelectContent>
                                                    {DEVELOPMENT_MODE_OPTIONS.map((option) => (
                                                        <SelectItemWithDescription 
                                                            key={option.value} 
                                                            value={option.value}
                                                            label={option.label}
                                                            description={option.description}
                                                        />
                                                    ))}
                                                </SelectContent>
                                            </Select>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                {developmentMode === 'SYNC_MODE' && (
                                    <FormField
                                        control={form.control}
                                        name="enableGitSyncCheck"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>Git同步检测</FormLabel>
                                                <FormControl>
                                                    <div className="flex items-center gap-2 h-10">
                                                        <Switch
                                                            checked={field.value}
                                                            onCheckedChange={field.onChange}
                                                        />
                                                        <span className="text-sm text-muted-foreground">
                                                            {field.value ? '启用' : '禁用'}
                                                        </span>
                                                    </div>
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                )}

                                <div className="grid grid-cols-2 gap-4">
                                    <FormField
                                        control={form.control}
                                        name="enabled"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>状态</FormLabel>
                                                <FormControl>
                                                    <div className="flex items-center gap-2 h-10">
                                                        <Switch
                                                            checked={field.value}
                                                            onCheckedChange={field.onChange}
                                                        />
                                                        <span className="text-sm text-muted-foreground">
                                                            {field.value ? '启用' : '禁用'}
                                                        </span>
                                                    </div>
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    <FormField
                                        control={form.control}
                                        name="sort"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>排序</FormLabel>
                                                <FormControl>
                                                    <Input
                                                        {...field}
                                                        type="number"
                                                        min={0}
                                                        onChange={(e) => field.onChange(Number(e.target.value))}
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>

                        </form>
                    </Form>
                </DialogBody>
                <DialogFooter>
                    <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
                        取消
                    </Button>
                    <Button
                        type="button"
                        onClick={async () => {
                            const isValid = await form.trigger();
                            if (isValid) {
                                handleSubmit(form.getValues());
                            }
                        }}
                    >
                        确定
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
};

export default TeamModal;

