import React, {useEffect, useState} from 'react';
import type {Application, RepositoryGroup, RepositoryProject} from '../types';
import {DevelopmentLanguageTypeEnum} from '../types';
import {createApplication, updateApplication, getRepositoryGroupList, getRepositoryProjects} from '../service';
import type {ExternalSystemResponse} from '@/pages/Deploy/External/types';
import {SystemType} from '@/pages/Deploy/External/types';
import {getExternalSystems} from '@/pages/Deploy/External/service';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    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,
    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 {applicationFormSchema, type ApplicationFormValues} from "../schema";
import {Textarea} from "@/components/ui/textarea";
import {Command, CommandEmpty, CommandGroup, CommandInput, CommandItem} from "@/components/ui/command";
import {ScrollArea} from "@/components/ui/scroll-area";
import {Check, ChevronDown, Search} from "lucide-react";
import {cn} from "@/lib/utils";
import {Popover, PopoverContent, PopoverTrigger} from "@/components/ui/popover";

interface ApplicationModalProps {
    open: boolean;
    onCancel: () => void;
    onSuccess: () => void;
    initialValues?: Application;
    projectGroupId: number;
}

const ApplicationModal: React.FC<ApplicationModalProps> = ({
    open,
    onCancel,
    onSuccess,
    initialValues,
    projectGroupId,
}) => {
    const [externalSystems, setExternalSystems] = useState<ExternalSystemResponse[]>([]);
    const [repositoryGroups, setRepositoryGroups] = useState<RepositoryGroup[]>([]);
    const [repositoryProjects, setRepositoryProjects] = useState<RepositoryProject[]>([]);
    const {toast} = useToast();
    const isEdit = !!initialValues?.id;
    const [selectedExternalSystem, setSelectedExternalSystem] = useState<ExternalSystemResponse>();

    const form = useForm<ApplicationFormValues>({
        resolver: zodResolver(applicationFormSchema),
        defaultValues: {
            appCode: "",
            appName: "",
            appDesc: "",
            language: DevelopmentLanguageTypeEnum.JAVA,
            enabled: true,
            sort: 0,
            externalSystemId: undefined,
            repoGroupId: undefined,
            repoProjectId: undefined,
            projectGroupId,
        },
    });

    // 加载外部系统列表
    const loadExternalSystems = async () => {
        try {
            const response = await getExternalSystems({
                type: SystemType.GIT,
                enabled: true,
            });
            if (response?.content) {
                setExternalSystems(response.content);
            }
        } catch (error) {
            toast({
                variant: "destructive",
                title: "加载外部系统失败",
                description: error instanceof Error ? error.message : undefined,
                duration: 3000,
            });
        }
    };

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

    useEffect(() => {
        if (initialValues) {
            // 设置表单初始值
            form.reset({
                appCode: initialValues.appCode,
                appName: initialValues.appName,
                appDesc: initialValues.appDesc || "",
                language: initialValues.language,
                enabled: initialValues.enabled,
                sort: initialValues.sort,
                projectGroupId: initialValues.projectGroupId,
                externalSystemId: initialValues.externalSystemId,
                repoGroupId: initialValues.repoGroupId,
                repoProjectId: initialValues.repoProjectId
            });

            // 如果有外部系统ID，加载仓库组
            if (initialValues.externalSystemId) {
                fetchRepositoryGroups(initialValues.externalSystemId);
            }

            // 如果有仓库组ID，加载仓库项目
            if (initialValues.repoGroupId) {
                fetchRepositoryProjects(initialValues.repoGroupId);
            }
        }
    }, [initialValues]);

    // 当选择外部系统时，获取对应的仓库组列表
    const handleExternalSystemChange = (externalSystemId: number) => {
        form.setValue('repoGroupId', undefined);
        form.setValue('repoProjectId', undefined);
        setRepositoryProjects([]);
        fetchRepositoryGroups(externalSystemId);
    };

    const fetchRepositoryGroups = async (externalSystemId: number) => {
        const response = await getRepositoryGroupList(externalSystemId);
        setRepositoryGroups(response || []);
    };

    const fetchRepositoryProjects = async (repoGroupId: number) => {
        const response = await getRepositoryProjects(repoGroupId);
        setRepositoryProjects(response || []);
    };

    const handleSubmit = async (values: ApplicationFormValues) => {
        console.log('Form submitted with values:', values);
        try {
            if (isEdit) {
                await updateApplication({
                    ...values,
                    id: initialValues!.id,
                });
                toast({
                    title: "更新成功",
                    description: `应用 ${values.appName} 已更新`,
                    duration: 3000,
                });
            } else {
                await createApplication(values);
                toast({
                    title: "创建成功",
                    description: `应用 ${values.appName} 已创建`,
                    duration: 3000,
                });
            }
            onSuccess?.();
            onCancel();
        } catch (e) {
            console.error(e);
            toast({
                variant: "destructive",
                title: isEdit ? "更新失败" : "创建失败",
                description: e instanceof Error ? e.message : "操作失败，请重试",
                duration: 3000,
            });
        }
    };

    return (
        <Dialog open={open} onOpenChange={(open) => !open && onCancel()}>
            <DialogContent className="max-w-[800px] h-[75vh]">
                <DialogHeader className="pb-4">
                    <DialogTitle>{isEdit ? '编辑' : '新建'}应用</DialogTitle>
                </DialogHeader>
                <Form {...form}>
                    <form 
                        id="applicationForm" 
                        className="space-y-4 flex flex-col h-full"
                    >
                        <ScrollArea className="flex-1 -mx-6">
                            <div className="px-6 space-y-4">
                                <div className="grid grid-cols-3 gap-4">
                                    <FormField
                                        control={form.control}
                                        name="appCode"
                                        render={({field}) => (
                                            <FormItem>
                                                <FormLabel>应用编码</FormLabel>
                                                <FormControl>
                                                    <Input
                                                        disabled={isEdit}
                                                        placeholder="请输入应用编码"
                                                        {...field}
                                                    />
                                                </FormControl>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />

                                    <FormField
                                        control={form.control}
                                        name="appName"
                                        render={({field}) => (
                                            <FormItem>
                                                <FormLabel>应用名称</FormLabel>
                                                <FormControl>
                                                    <Input placeholder="请输入应用名称" {...field} />
                                                </FormControl>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />

                                    <FormField
                                        control={form.control}
                                        name="language"
                                        render={({field}) => (
                                            <FormItem>
                                                <FormLabel>开发语言</FormLabel>
                                                <Select
                                                    onValueChange={field.onChange}
                                                    defaultValue={field.value}
                                                >
                                                    <FormControl>
                                                        <SelectTrigger>
                                                            <SelectValue placeholder="请选择开发语言"/>
                                                        </SelectTrigger>
                                                    </FormControl>
                                                    <SelectContent>
                                                        {Object.entries(DevelopmentLanguageTypeEnum).map(([key, value]) => (
                                                            <SelectItem key={key} value={key}>
                                                                {value}
                                                            </SelectItem>
                                                        ))}
                                                    </SelectContent>
                                                </Select>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />
                                </div>

                                <div className="grid grid-cols-3 gap-4">
                                    <FormField
                                        control={form.control}
                                        name="externalSystemId"
                                        render={({field}) => (
                                            <FormItem>
                                                <FormLabel>外部系统</FormLabel>
                                                <Select
                                                    onValueChange={(value) => {
                                                        field.onChange(Number(value));
                                                        handleExternalSystemChange(Number(value));
                                                    }}
                                                    value={field.value?.toString()}
                                                >
                                                    <FormControl>
                                                        <SelectTrigger>
                                                            <SelectValue placeholder="请选择外部系统"/>
                                                        </SelectTrigger>
                                                    </FormControl>
                                                    <SelectContent>
                                                        {externalSystems.map((system) => (
                                                            <SelectItem
                                                                key={system.id}
                                                                value={system.id.toString()}
                                                            >
                                                                {system.name}
                                                            </SelectItem>
                                                        ))}
                                                    </SelectContent>
                                                </Select>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />

                                    <FormField
                                        control={form.control}
                                        name="repoGroupId"
                                        render={({field}) => {
                                            const [searchValue, setSearchValue] = React.useState("");
                                            const [open, setOpen] = React.useState(false);
                                            const filteredGroups = repositoryGroups.filter(group => 
                                                group.name.toLowerCase().includes(searchValue.toLowerCase())
                                            );
                                            
                                            return (
                                                <FormItem>
                                                    <FormLabel>代码仓库组</FormLabel>
                                                    <Popover open={open} onOpenChange={setOpen}>
                                                        <PopoverTrigger asChild>
                                                            <FormControl>
                                                                <Button
                                                                    variant="outline"
                                                                    role="combobox"
                                                                    disabled={!form.watch('externalSystemId')}
                                                                    className={cn(
                                                                        "w-full justify-between",
                                                                        !field.value && "text-muted-foreground"
                                                                    )}
                                                                >
                                                                    {field.value
                                                                        ? repositoryGroups.find(
                                                                            (group) => group.repoGroupId === field.value
                                                                        )?.fullName || "请选择代码仓库组"
                                                                        : !form.watch('externalSystemId')
                                                                            ? "请先选择外部系统"
                                                                            : "请选择代码仓库组"}
                                                                    <ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                                                                </Button>
                                                            </FormControl>
                                                        </PopoverTrigger>
                                                        <PopoverContent className="w-[--radix-popover-trigger-width] p-0">
                                                            <div className="flex items-center border-b px-3">
                                                                <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
                                                                <input
                                                                    placeholder="搜索代码仓库组..."
                                                                    className="flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50"
                                                                    value={searchValue}
                                                                    onChange={(e) => setSearchValue(e.target.value)}
                                                                />
                                                            </div>
                                                            <div className="relative">
                                                                <ScrollArea className="h-[200px] w-full">
                                                                    <div className="p-1">
                                                                        {filteredGroups.length === 0 ? (
                                                                            <div className="p-4 text-center text-sm text-muted-foreground">
                                                                                未找到代码仓库组
                                                                            </div>
                                                                        ) : (
                                                                            filteredGroups.map((group) => (
                                                                                <div
                                                                                    key={group.repoGroupId}
                                                                                    className={cn(
                                                                                        "relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground",
                                                                                        group.repoGroupId === field.value && "bg-accent text-accent-foreground"
                                                                                    )}
                                                                                    onClick={() => {
                                                                                        form.setValue("repoGroupId", group.repoGroupId);
                                                                                        form.setValue("repoProjectId", undefined);
                                                                                        setRepositoryProjects([]);
                                                                                        fetchRepositoryProjects(group.repoGroupId);
                                                                                        setSearchValue("");
                                                                                        setOpen(false);
                                                                                    }}
                                                                                    onWheel={(e) => {
                                                                                        const scrollArea = e.currentTarget.closest('[data-radix-scroll-area-viewport]');
                                                                                        if (scrollArea) {
                                                                                            scrollArea.scrollTop += e.deltaY;
                                                                                        }
                                                                                    }}
                                                                                >
                                                                                    <div className="flex flex-col">
                                                                                        <span className="font-medium">{group.fullName}</span>
                                                                                        <span className="text-xs text-muted-foreground truncate">
                                                                                            {group.fullPath}
                                                                                        </span>
                                                                                    </div>
                                                                                    {group.repoGroupId === field.value && (
                                                                                        <Check className="ml-auto h-4 w-4" />
                                                                                    )}
                                                                                </div>
                                                                            ))
                                                                        )}
                                                                    </div>
                                                                </ScrollArea>
                                                            </div>
                                                        </PopoverContent>
                                                    </Popover>
                                                    <FormMessage />
                                                </FormItem>
                                            );
                                        }}
                                    />

                                    <FormField
                                        control={form.control}
                                        name="repoProjectId"
                                        render={({field}) => {
                                            const [searchValue, setSearchValue] = React.useState("");
                                            const [open, setOpen] = React.useState(false);
                                            const filteredProjects = repositoryProjects.filter(project => 
                                                project.name.toLowerCase().includes(searchValue.toLowerCase())
                                            );
                                            
                                            return (
                                                <FormItem>
                                                    <FormLabel>项目</FormLabel>
                                                    <Popover open={open} onOpenChange={setOpen}>
                                                        <PopoverTrigger asChild>
                                                            <FormControl>
                                                                <Button
                                                                    variant="outline"
                                                                    role="combobox"
                                                                    disabled={!form.watch('repoGroupId')}
                                                                    className={cn(
                                                                        "w-full justify-between",
                                                                        !field.value && "text-muted-foreground"
                                                                    )}
                                                                >
                                                                    {field.value
                                                                        ? repositoryProjects.find(
                                                                            (project) => project.repoProjectId === field.value
                                                                        )?.name
                                                                        : !form.watch('repoGroupId')
                                                                            ? "请先选择代码仓库组"
                                                                            : "请选择项目"}
                                                                    <ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                                                                </Button>
                                                            </FormControl>
                                                        </PopoverTrigger>
                                                        <PopoverContent className="w-[--radix-popover-trigger-width] p-0">
                                                            <div className="flex items-center border-b px-3">
                                                                <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
                                                                <input
                                                                    placeholder="搜索项目..."
                                                                    className="flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50"
                                                                    value={searchValue}
                                                                    onChange={(e) => setSearchValue(e.target.value)}
                                                                />
                                                            </div>
                                                            <div className="relative">
                                                                <ScrollArea className="h-[200px] w-full">
                                                                    <div className="p-1">
                                                                        {filteredProjects.length === 0 ? (
                                                                            <div className="p-4 text-center text-sm text-muted-foreground">
                                                                                未找到项目
                                                                            </div>
                                                                        ) : (
                                                                            filteredProjects.map((project) => (
                                                                                <div
                                                                                    key={project.repoProjectId}
                                                                                    className={cn(
                                                                                        "relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground",
                                                                                        project.id === field.value && "bg-accent text-accent-foreground"
                                                                                    )}
                                                                                    onClick={() => {
                                                                                        form.setValue("repoProjectId", project.repoProjectId);
                                                                                        setSearchValue("");
                                                                                        setOpen(false);
                                                                                    }}
                                                                                    onWheel={(e) => {
                                                                                        const scrollArea = e.currentTarget.closest('[data-radix-scroll-area-viewport]');
                                                                                        if (scrollArea) {
                                                                                            scrollArea.scrollTop += e.deltaY;
                                                                                        }
                                                                                    }}
                                                                                >
                                                                                    {project.name}
                                                                                    {project.repoProjectId === field.value && (
                                                                                        <Check className="ml-auto h-4 w-4" />
                                                                                    )}
                                                                                </div>
                                                                            ))
                                                                        )}
                                                                    </div>
                                                                </ScrollArea>
                                                            </div>
                                                        </PopoverContent>
                                                    </Popover>
                                                    <FormMessage />
                                                </FormItem>
                                            );
                                        }}
                                    />
                                </div>
                                <FormField
                                    control={form.control}
                                    name="appDesc"
                                    render={({field}) => (
                                        <FormItem>
                                            <FormLabel>应用描述</FormLabel>
                                            <FormControl>
                                                <Textarea
                                                    {...field}
                                                    placeholder="请输入应用描述"
                                                    rows={4}
                                                />
                                            </FormControl>
                                            <FormMessage/>
                                        </FormItem>
                                    )}
                                />

                                <FormField
                                    control={form.control}
                                    name="enabled"
                                    render={({field}) => (
                                        <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                                            <div className="space-y-0.5">
                                                <FormLabel>状态</FormLabel>
                                            </div>
                                            <FormControl>
                                                <Switch
                                                    checked={field.value}
                                                    onCheckedChange={field.onChange}
                                                />
                                            </FormControl>
                                        </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 className="h-4" />
                            </div>
                        </ScrollArea>
                        <DialogFooter className="pt-4">
                            <Button type="button" variant="outline" onClick={onCancel}>
                                取消
                            </Button>
                            <Button 
                                type="button"
                                onClick={() => {
                                    console.log('Submit button clicked');
                                    console.log('Form values:', form.getValues());
                                    const isValid = form.trigger();
                                    console.log('Form validation result:', isValid);
                                    if (isValid) {
                                        handleSubmit(form.getValues());
                                    }
                                }}
                            >
                                确定
                            </Button>
                        </DialogFooter>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    );
};

export default ApplicationModal;
