/**
 * 通知渠道表单管理Hook
 */
import { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useToast } from '@/components/ui/use-toast';
import { NotificationChannelType } from '../../types';
import type { NotificationChannel } from '../../types';
import type { ConfigState } from '../config-strategies/types';
import { ConfigStrategyFactory } from '../config-strategies/ConfigStrategyFactory';
import { createChannel, updateChannel, getChannelById } from '../../service';
import { formSchema, type FormValues } from '../schemas/formSchema';

interface UseNotificationChannelFormProps {
  open: boolean;
  editId?: number;
  onSuccess: () => void;
  onOpenChange: (open: boolean) => void;
}

export const useNotificationChannelForm = ({
  open,
  editId,
  onSuccess,
  onOpenChange,
}: UseNotificationChannelFormProps) => {
  const { toast } = useToast();
  
  // 基础状态
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [selectedType, setSelectedType] = useState<NotificationChannelType>(
    NotificationChannelType.WEWORK
  );
  const [currentEnabled, setCurrentEnabled] = useState<boolean>(true);
  const [configState, setConfigState] = useState<ConfigState>({});

  // 表单管理
  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    mode: 'onChange',
    defaultValues: {
      channelType: NotificationChannelType.WEWORK,
      config: ConfigStrategyFactory.getStrategy(NotificationChannelType.WEWORK).getDefaultConfig(),
    },
  });

  const { register, handleSubmit, formState: { errors, isValid }, reset, setValue, watch } = form;
  const mode = editId ? 'edit' : 'create';

  // 监听渠道类型变化
  const watchedType = watch('channelType');
  useEffect(() => {
    if (watchedType && watchedType !== selectedType) {
      setSelectedType(watchedType);
      
      // 切换类型时重置配置和状态
      const strategy = ConfigStrategyFactory.getStrategy(watchedType);
      setValue('config', strategy.getDefaultConfig());
      setConfigState(strategy.loadFromData({ channelType: watchedType, config: {} }));
    }
  }, [watchedType, selectedType, setValue]);

  // 对话框打开/关闭处理
  useEffect(() => {
    if (open && editId) {
      loadChannelData();
    } else if (open) {
      resetForm();
    }
  }, [open, editId]);

  // 重置表单
  const resetForm = () => {
    const defaultType = NotificationChannelType.WEWORK;
    const strategy = ConfigStrategyFactory.getStrategy(defaultType);
    
    reset({
      name: '',
      channelType: defaultType,
      config: strategy.getDefaultConfig(),
      description: '',
    });
    
    setSelectedType(defaultType);
    setConfigState(strategy.loadFromData({ channelType: defaultType, config: {} }));
    setCurrentEnabled(true);
  };

  // 加载编辑数据
  const loadChannelData = async () => {
    if (!editId) return;
    
    setLoading(true);
    try {
      const data = await getChannelById(editId);
      
      reset({
        name: data.name,
        channelType: data.channelType,
        config: data.config,
        description: data.description || '',
      });
      
      setSelectedType(data.channelType);
      setCurrentEnabled(data.enabled);
      
      // 使用策略加载配置状态
      const strategy = ConfigStrategyFactory.getStrategy(data.channelType);
      setConfigState(strategy.loadFromData(data));
      
    } catch (error: any) {
      toast({
        variant: 'destructive',
        title: '加载失败',
        description: error.response?.data?.message || error.message,
      });
      onOpenChange(false);
    } finally {
      setLoading(false);
    }
  };

  // 提交表单
  const onSubmit = async (values: FormValues) => {
    setSaving(true);
    try {
      // 使用策略构建配置
      const strategy = ConfigStrategyFactory.getStrategy(selectedType);
      const config = strategy.buildConfig(configState, values.config);
      
      const payload: NotificationChannel = {
        name: values.name,
        channelType: values.channelType,
        config,
        description: values.description,
        enabled: mode === 'create' ? true : currentEnabled,
      };
      
      if (mode === 'edit' && editId) {
        await updateChannel(editId, payload);
        toast({ title: '更新成功' });
      } else {
        await createChannel(payload);
        toast({ title: '创建成功' });
      }
      
      onSuccess();
      onOpenChange(false);
    } catch (error: any) {
      toast({
        variant: 'destructive',
        title: mode === 'edit' ? '更新失败' : '创建失败',
        description: error.response?.data?.message || error.message,
      });
    } finally {
      setSaving(false);
    }
  };

  // 更新配置状态
  const updateConfigState = (updates: Partial<ConfigState>) => {
    setConfigState(prev => ({ ...prev, ...updates }));
  };

  return {
    // 状态
    loading,
    saving,
    selectedType,
    configState,
    mode,
    
    // 表单
    register,
    handleSubmit,
    errors,
    isValid,
    setValue,
    
    // 方法
    onSubmit,
    updateConfigState,
  };
};
