import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogBody,
} from '@/components/ui/dialog';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Badge } from '@/components/ui/badge';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import { useToast } from '@/components/ui/use-toast';
import { Check, ChevronsUpDown, Loader2, X } from 'lucide-react';
import type { Environment } from '@/pages/Deploy/Environment/List/types';
import {
  getTeamEnvironmentConfig,
  createTeamEnvironmentConfig,
  updateTeamEnvironmentConfig,
} from '../service';

interface User {
  id: number;
  username: string;
  realName?: string;
}

// 表单验证 Schema
const formSchema = z.object({
  environmentId: z.number().min(1, '请选择环境'),
  approvalRequired: z.boolean().default(false),
  approverUserIds: z.array(z.number()).default([]),
  requireCodeReview: z.boolean().default(false),
  remark: z.string().max(100, '备注最多100个字符').optional(),
}).refine(
  (data) => {
    // 如果需要审批，则审批人必填
    if (data.approvalRequired && (!data.approverUserIds || data.approverUserIds.length === 0)) {
      return false;
    }
    return true;
  },
  {
    message: '需要审批时必须选择审批人',
    path: ['approverUserIds'],
  }
);

type FormData = z.infer<typeof formSchema>;

interface TeamEnvironmentConfigDialogProps{
  open: boolean;
  onOpenChange: (open: boolean) => void;
  teamId: number;
  environments: Environment[];
  users?: User[];
  onSuccess?: () => void;
  // 编辑模式：传入要编辑的环境ID
  editEnvironmentId?: number;
  // 旧的初始数据模式（向后兼容）
  initialData?: {
    environmentId: number;
    workflowDefinitionId?: number;
    requireCodeReview?: boolean;
    remark?: string;
  };
}

export const TeamEnvironmentConfigDialog: React.FC<
  TeamEnvironmentConfigDialogProps
> = ({
  open,
  onOpenChange,
  teamId,
  environments,
  users = [],
  onSuccess,
  editEnvironmentId,
  initialData,
}) => {
  const { toast } = useToast();
  const [submitting, setSubmitting] = useState(false);
  const [loading, setLoading] = useState(false);
  const [configId, setConfigId] = useState<number | null>(null);

  const form = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      environmentId: initialData?.environmentId || editEnvironmentId || 0,
      approvalRequired: false,
      approverUserIds: [],
      requireCodeReview: initialData?.requireCodeReview || false,
      remark: initialData?.remark || '',
    },
  });

  // 对话框打开时初始化
  useEffect(() => {
    if (open) {
      
      if (editEnvironmentId) {
        // 编辑模式或绑定新环境：设置环境ID并加载配置
        form.setValue('environmentId', editEnvironmentId);
        loadEnvironmentConfig();
      } else if (initialData) {
        // 旧模式兼容
        setConfigId(null);
        form.reset({
          environmentId: initialData.environmentId,
          approvalRequired: false,
          approverUserIds: [],
          requireCodeReview: initialData.requireCodeReview || false,
          remark: initialData.remark || '',
        });
      } else {
        // 创建模式：清空表单
        setConfigId(null);
        form.reset({
          environmentId: 0,
          approvalRequired: false,
          approverUserIds: [],
          requireCodeReview: false,
          remark: '',
        });
      }
    }
  }, [open, editEnvironmentId, teamId]);

  const loadEnvironmentConfig = async () => {
    if (!editEnvironmentId) return;
    
    setLoading(true);
    try {
      const config = await getTeamEnvironmentConfig(teamId, editEnvironmentId);
      
      if (config) {
        setConfigId(config.id);
        form.reset({
          environmentId: config.environmentId,
          approvalRequired: config.approvalRequired || false,
          approverUserIds: config.approverUserIds || [],
          requireCodeReview: config.requireCodeReview || false,
          remark: config.remark || '',
        });
      }
    } catch (error: any) {
      // 如果找不到配置（404），说明是首次配置该环境
      if (error.response?.status === 404) {
        setConfigId(null);
        form.reset({
          environmentId: editEnvironmentId,
          approvalRequired: false,
          approverUserIds: [],
          requireCodeReview: false,
          remark: '',
        });
      } else {
        toast({
          title: '加载失败',
          description: error.message || '无法加载环境配置',
          variant: 'destructive',
        });
      }
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (data: FormData) => {
    console.log('表单提交开始', data);
    setSubmitting(true);
    try {
      const payload = {
        teamId,
        environmentId: data.environmentId,
        approvalRequired: data.approvalRequired,
        // 如果不需要审批，清空审批人列表
        approverUserIds: data.approvalRequired ? data.approverUserIds : [],
        requireCodeReview: data.requireCodeReview,
        remark: data.remark,
      };

      console.log('提交数据', payload);

      if (configId) {
        // 更新已有配置
        await updateTeamEnvironmentConfig(configId, payload);
        toast({
          title: '保存成功',
          description: '环境配置已更新',
        });
      } else {
        // 创建新配置
        await createTeamEnvironmentConfig(payload);
        toast({
          title: '保存成功',
          description: '环境配置已创建',
        });
      }

      onOpenChange(false);
      onSuccess?.();
    } catch (error: any) {
      console.error('保存失败', error);
      toast({
        title: '保存失败',
        description: error.message || '保存环境配置失败',
        variant: 'destructive',
      });
    } finally {
      setSubmitting(false);
    }
  };

  const handleSaveClick = () => {
    console.log('保存按钮被点击');
    console.log('表单值', form.getValues());
    console.log('表单错误', form.formState.errors);
    form.handleSubmit(handleSubmit)();
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>
            {editEnvironmentId ? '编辑环境配置' : '配置环境'}
          </DialogTitle>
          <DialogDescription>
            {editEnvironmentId 
              ? '修改环境的审批流程、通知设置等配置信息'
              : '为环境配置审批流程、通知设置等信息'}
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <DialogBody>
            <div className="flex items-center justify-center h-64">
              <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
            </div>
          </DialogBody>
        ) : (
          <Form {...form}>
            <DialogBody>
              <div className="space-y-6">
                {/* 环境选择 */}
                <FormField
                  control={form.control}
                  name="environmentId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>环境 *</FormLabel>
                      <Select
                        value={field.value?.toString() || ''}
                        onValueChange={(value) => field.onChange(Number(value))}
                        disabled={!!initialData || !!editEnvironmentId}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="请选择环境" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {environments.map((env) => (
                            <SelectItem key={env.id} value={env.id.toString()}>
                              {env.envName}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* 是否需要审批 */}
                <FormField
                  control={form.control}
                  name="approvalRequired"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                      <div className="space-y-0.5">
                        <FormLabel className="text-base">需要审批</FormLabel>
                        <div className="text-sm text-muted-foreground">
                          部署前需要通过审批流程
                        </div>
                      </div>
                      <FormControl>
                        <Switch
                          checked={field.value}
                          onCheckedChange={(checked) => {
                            field.onChange(checked);
                            // 取消审批时自动清空审批人列表
                            if (!checked) {
                              form.setValue('approverUserIds', []);
                            }
                          }}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />

                {/* 审批人多选 - 仅在需要审批时显示 */}
                {form.watch('approvalRequired') && (
                  <FormField
                    control={form.control}
                    name="approverUserIds"
                    render={({ field }) => {
                      const [open, setOpen] = useState(false);
                      const selectedUsers = (users || []).filter(u => field.value?.includes(u.id));
                      
                      return (
                        <FormItem className="flex flex-col">
                          <FormLabel>审批人 *</FormLabel>
                          <Popover open={open} onOpenChange={setOpen}>
                            <PopoverTrigger asChild>
                              <FormControl>
                                <Button
                                  type="button"
                                  variant="outline"
                                  role="combobox"
                                  aria-expanded={open}
                                  className="w-full justify-between"
                                >
                                  {selectedUsers.length > 0 ? (
                                    <div className="flex gap-1 flex-wrap">
                                      {selectedUsers.map((user) => (
                                        <Badge
                                          key={user.id}
                                          variant="secondary"
                                          className="mr-1"
                                        >
                                          {user.realName || user.username}
                                          <span
                                            role="button"
                                            tabIndex={0}
                                            className="ml-1 cursor-pointer ring-offset-background rounded-full outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 hover:bg-muted"
                                            onKeyDown={(e) => {
                                              if (e.key === "Enter" || e.key === " ") {
                                                e.preventDefault();
                                                field.onChange(field.value?.filter(id => id !== user.id) || []);
                                              }
                                            }}
                                            onMouseDown={(e) => {
                                              e.preventDefault();
                                              e.stopPropagation();
                                            }}
                                            onClick={(e) => {
                                              e.stopPropagation();
                                              field.onChange(field.value?.filter(id => id !== user.id) || []);
                                            }}
                                          >
                                            <X className="h-3 w-3 text-muted-foreground hover:text-foreground" />
                                          </span>
                                        </Badge>
                                      ))}
                                    </div>
                                  ) : (
                                    "请选择审批人"
                                  )}
                                  <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                                </Button>
                              </FormControl>
                            </PopoverTrigger>
                            <PopoverContent className="w-full p-0" align="start">
                              <Command>
                                <CommandInput placeholder="搜索审批人..." />
                                <CommandList>
                                  <CommandEmpty>未找到审批人</CommandEmpty>
                                  <CommandGroup>
                                    {(users || []).map((user) => {
                                      const isSelected = field.value?.includes(user.id);
                                      return (
                                        <CommandItem
                                          key={user.id}
                                          value={`${user.id}-${user.username}-${user.realName || ''}`}
                                          onSelect={() => {
                                            const newValue = isSelected
                                              ? field.value?.filter(id => id !== user.id) || []
                                              : [...(field.value || []), user.id];
                                            field.onChange(newValue);
                                          }}
                                        >
                                          <Check
                                            className={`mr-2 h-4 w-4 ${
                                              isSelected ? "opacity-100" : "opacity-0"
                                            }`}
                                          />
                                          {user.realName || user.username}
                                        </CommandItem>
                                      );
                                    })}
                                  </CommandGroup>
                                </CommandList>
                              </Command>
                            </PopoverContent>
                          </Popover>
                          <FormMessage />
                        </FormItem>
                      );
                    }}
                  />
                )}

                {/* 需要代码审查 */}
                <FormField
                  control={form.control}
                  name="requireCodeReview"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                      <div className="space-y-0.5">
                        <FormLabel className="text-base">需要代码审查</FormLabel>
                        <div className="text-sm text-muted-foreground">
                          部署前需要通过代码审查
                        </div>
                      </div>
                      <FormControl>
                        <Switch
                          checked={field.value}
                          onCheckedChange={field.onChange}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />

                {/* 备注 */}
                <FormField
                  control={form.control}
                  name="remark"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>备注</FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder="请输入备注信息（最多100字符）"
                          className="resize-none"
                          rows={3}
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </DialogBody>

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={submitting}
              >
                取消
              </Button>
              <Button
                type="button"
                onClick={handleSaveClick}
                disabled={submitting || loading}
              >
                {submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                保存
              </Button>
            </DialogFooter>
          </Form>
        )}
      </DialogContent>
    </Dialog>
  );
};
