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,
  DialogFooter,
  DialogBody,
  DialogDescription,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import {
  ClearableSelect,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useToast } from '@/components/ui/use-toast';
import { Loader2 } from 'lucide-react';
import {
  getTeamEnvironmentConfig,
  updateTeamEnvironmentConfig,
  getNotificationChannels,
  getNotificationTemplates,
} from '../service';

// 表单验证 Schema
const formSchema = z
  .object({
    notificationConfig: z
      .object({
        id: z.number().optional(),
        notificationChannelId: z.number().nullish(),
        preApprovalNotificationEnabled: z.boolean().default(false),
        preApprovalNotificationTemplateId: z.number().nullish(),
        buildNotificationEnabled: z.boolean().default(false),
        buildNotificationTemplateId: z.number().nullish(),
        buildFailureFileEnabled: z.boolean().default(false),
      })
      .optional(),
  })
  .refine(
    (data) => {
      // 如果启用了任意通知类型，则通知渠道必填
      if (
        (data.notificationConfig?.preApprovalNotificationEnabled ||
          data.notificationConfig?.buildNotificationEnabled ||
          data.notificationConfig?.buildFailureFileEnabled) &&
        !data.notificationConfig?.notificationChannelId
      ) {
        return false;
      }
      return true;
    },
    {
      message: '启用通知时必须选择通知渠道',
      path: ['notificationConfig', 'notificationChannelId'],
    }
  );

type FormData = z.infer<typeof formSchema>;

interface NotificationChannel {
  id: number;
  name: string;
  channelType: string;
  enabled?: boolean;
  description?: string;
}

interface NotificationTemplate {
  id: number;
  name: string;
  type?: string;
}

interface NotificationConfigDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  teamId: number;
  environmentId: number;
  environmentName: string;
  onSuccess?: () => void;
}

export const NotificationConfigDialog: React.FC<
  NotificationConfigDialogProps
> = ({ open, onOpenChange, teamId, environmentId, environmentName, onSuccess }) => {
  const { toast } = useToast();
  const [submitting, setSubmitting] = useState(false);
  const [loading, setLoading] = useState(false);
  const [configId, setConfigId] = useState<number | null>(null);
  const [currentConfig, setCurrentConfig] = useState<any>(null);
  const [notificationChannels, setNotificationChannels] = useState<
    NotificationChannel[]
  >([]);
  const [loadingChannels, setLoadingChannels] = useState(false);
  const [notificationTemplates, setNotificationTemplates] = useState<
    NotificationTemplate[]
  >([]);
  const [loadingTemplates, setLoadingTemplates] = useState(false);

  const form = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      notificationConfig: {
        notificationChannelId: undefined,
        preApprovalNotificationEnabled: false,
        preApprovalNotificationTemplateId: undefined,
        buildNotificationEnabled: false,
        buildNotificationTemplateId: undefined,
        buildFailureFileEnabled: false,
      },
    },
  });

  // 加载通知渠道列表
  const loadNotificationChannels = async () => {
    setLoadingChannels(true);
    try {
      const channels = await getNotificationChannels();
      setNotificationChannels(channels || []);
    } catch (error: any) {
      toast({
        title: '加载失败',
        description: error.message || '无法加载通知渠道列表',
        variant: 'destructive',
      });
    } finally {
      setLoadingChannels(false);
    }
  };

  // 加载通知模板列表
  const loadNotificationTemplates = async (channelType?: string) => {
    setLoadingTemplates(true);
    try {
      const templates = await getNotificationTemplates(channelType);
      setNotificationTemplates(templates || []);
    } catch (error: any) {
      toast({
        title: '加载失败',
        description: error.message || '无法加载通知模板列表',
        variant: 'destructive',
      });
    } finally {
      setLoadingTemplates(false);
    }
  };

  // 加载环境配置
  const loadEnvironmentConfig = async () => {
    setLoading(true);
    try {
      const config = await getTeamEnvironmentConfig(teamId, environmentId);

      if (config) {
        setConfigId(config.id);
        setCurrentConfig(config);
        form.reset({
          notificationConfig: config.notificationConfig || {
            notificationChannelId: undefined,
            preApprovalNotificationEnabled: false,
            preApprovalNotificationTemplateId: undefined,
            buildNotificationEnabled: false,
            buildNotificationTemplateId: undefined,
            buildFailureFileEnabled: false,
          },
        });
      }
    } catch (error: any) {
      if (error.response?.status === 404) {
        toast({
          title: '提示',
          description: '请先配置该环境的基本信息',
          variant: 'destructive',
        });
        onOpenChange(false);
      } else {
        toast({
          title: '加载失败',
          description: error.message || '无法加载环境配置',
          variant: 'destructive',
        });
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (open) {
      loadNotificationChannels();
      loadEnvironmentConfig();
    }
  }, [open, teamId, environmentId]);

  const selectedChannelId = form.watch('notificationConfig.notificationChannelId');
  
  useEffect(() => {
    if (open && notificationChannels.length > 0) {
      const selectedChannel = notificationChannels.find(
        (channel) => channel.id === selectedChannelId
      );
      loadNotificationTemplates(selectedChannel?.channelType);
    }
  }, [selectedChannelId, notificationChannels, open]);

  const handleSubmit = async (data: FormData) => {
    if (!configId || !currentConfig) {
      toast({
        title: '错误',
        description: '请先配置该环境的基本信息',
        variant: 'destructive',
      });
      return;
    }

    setSubmitting(true);
    try {
      let notificationConfig = undefined;
      if (data.notificationConfig?.notificationChannelId) {
        notificationConfig = {
          id: data.notificationConfig.id,
          notificationChannelId: data.notificationConfig.notificationChannelId,
          preApprovalNotificationEnabled: data.notificationConfig.preApprovalNotificationEnabled ?? false,
          preApprovalNotificationTemplateId: data.notificationConfig.preApprovalNotificationTemplateId ?? undefined,
          buildNotificationEnabled: data.notificationConfig.buildNotificationEnabled ?? false,
          buildNotificationTemplateId: data.notificationConfig.buildNotificationTemplateId ?? undefined,
          buildFailureFileEnabled: data.notificationConfig.buildFailureFileEnabled ?? false,
        };
      }
      
      const payload = {
        teamId: currentConfig.teamId,
        environmentId: currentConfig.environmentId,
        approvalRequired: currentConfig.approvalRequired,
        approverUserIds: currentConfig.approverUserIds || [],
        requireCodeReview: currentConfig.requireCodeReview,
        remark: currentConfig.remark,
        notificationConfig,
      };

      await updateTeamEnvironmentConfig(configId, payload);

      toast({
        title: '保存成功',
        description: '通知配置已更新',
      });

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

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl">
        <DialogHeader>
          <DialogTitle>通知配置</DialogTitle>
          <DialogDescription>
            配置 {environmentName} 环境的通知设置
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <DialogBody>
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
            </div>
          </DialogBody>
        ) : (
          <Form {...form}>
            <form onSubmit={form.handleSubmit(handleSubmit)}>
              <DialogBody className="space-y-4">
                {/* 通知渠道选择 */}
                <FormField
                  control={form.control}
                  name="notificationConfig.notificationChannelId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>通知渠道</FormLabel>
                      <ClearableSelect
                        value={field.value}
                        onValueChange={(value) =>
                          field.onChange(value ? Number(value) : null)
                        }
                        disabled={loadingChannels}
                      >
                        <FormControl>
                          <SelectTrigger
                            clearable
                            hasValue={!!field.value}
                            onClear={() => field.onChange(null)}
                          >
                            <SelectValue
                              placeholder={loadingChannels ? '加载中...' : '请选择通知渠道'}
                            />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {notificationChannels.map((channel) => (
                            <SelectItem key={channel.id} value={channel.id.toString()}>
                              {channel.name} ({channel.channelType})
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </ClearableSelect>
                      <FormMessage />
                      <div className="text-sm text-muted-foreground">
                        选择通知渠道后，启用下方的通知类型
                      </div>
                    </FormItem>
                  )}
                />

                {/* 审批前提醒 */}
                <div className="rounded-lg border p-4 space-y-2">
                  <div className="grid grid-cols-[1fr_auto_1fr] gap-4 items-center">
                    <div>
                      <FormLabel className="text-base">审批前提醒</FormLabel>
                    </div>
                    <FormField
                      control={form.control}
                      name="notificationConfig.preApprovalNotificationEnabled"
                      render={({ field }) => (
                        <FormItem className="mb-0">
                          <FormControl>
                            <Switch checked={field.value} onCheckedChange={field.onChange} />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="notificationConfig.preApprovalNotificationTemplateId"
                      render={({ field }) => (
                        <FormItem className="mb-0">
                          <FormControl>
                            <ClearableSelect
                              value={field.value?.toString()}
                              onValueChange={(value) => field.onChange(value ? Number(value) : null)}
                              disabled={loadingTemplates}
                            >
                              <SelectTrigger clearable hasValue={!!field.value} onClear={() => field.onChange(null)}>
                                <SelectValue placeholder={loadingTemplates ? '加载中...' : '请选择通知模板（可选）'} />
                              </SelectTrigger>
                              <SelectContent>
                                {notificationTemplates.map((template) => (
                                  <SelectItem key={template.id} value={template.id.toString()}>
                                    {template.name}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </ClearableSelect>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                  <div className="grid grid-cols-[1fr_auto_1fr] gap-4">
                    <div className="text-sm text-muted-foreground">提交部署申请进入审批时发送通知</div>
                    <div></div>
                    <div className="text-sm text-muted-foreground">审批前提醒模板</div>
                  </div>
                </div>

                {/* 构建通知 */}
                <div className="rounded-lg border p-4 space-y-2">
                  <div className="grid grid-cols-[1fr_auto_1fr] gap-4 items-center">
                    <div>
                      <FormLabel className="text-base">构建通知</FormLabel>
                    </div>
                    <FormField
                      control={form.control}
                      name="notificationConfig.buildNotificationEnabled"
                      render={({ field }) => (
                        <FormItem className="mb-0">
                          <FormControl>
                            <Switch checked={field.value} onCheckedChange={field.onChange} />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="notificationConfig.buildNotificationTemplateId"
                      render={({ field }) => (
                        <FormItem className="mb-0">
                          <FormControl>
                            <ClearableSelect
                              value={field.value?.toString()}
                              onValueChange={(value) => field.onChange(value ? Number(value) : null)}
                              disabled={loadingTemplates}
                            >
                              <SelectTrigger clearable hasValue={!!field.value} onClear={() => field.onChange(null)}>
                                <SelectValue placeholder={loadingTemplates ? '加载中...' : '请选择通知模板（可选）'} />
                              </SelectTrigger>
                              <SelectContent>
                                {notificationTemplates.map((template) => (
                                  <SelectItem key={template.id} value={template.id.toString()}>
                                    {template.name}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </ClearableSelect>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                  <div className="grid grid-cols-[1fr_auto_1fr] gap-4">
                    <div className="text-sm text-muted-foreground">构建状态变更时发送通知</div>
                    <div></div>
                    <div className="text-sm text-muted-foreground">构建通知模板</div>
                  </div>
                </div>

                {/* 失败日志 */}
                <div className="rounded-lg border p-4 space-y-2">
                  <div className="grid grid-cols-[1fr_auto_1fr] gap-4 items-center">
                    <div>
                      <FormLabel className="text-base">失败日志</FormLabel>
                    </div>
                    <FormField
                      control={form.control}
                      name="notificationConfig.buildFailureFileEnabled"
                      render={({ field }) => (
                        <FormItem className="mb-0">
                          <FormControl>
                            <Switch checked={field.value} onCheckedChange={field.onChange} />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                    <div></div>
                  </div>
                  <div className="grid grid-cols-[1fr_auto_1fr] gap-4">
                    <div className="text-sm text-muted-foreground">构建失败时是否发送日志文件</div>
                    <div></div>
                    <div></div>
                  </div>
                </div>
              </DialogBody>

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