/**
 * 通知渠道对话框组件
 * 
 * 应用的设计模式：
 * 1. 策略模式 - 不同渠道类型的配置处理
 * 2. 工厂模式 - 创建配置组件和策略
 * 3. 组合模式 - 将大组件拆分为小组件
 * 4. 自定义Hook模式 - 提取状态管理逻辑
 */
import React from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogBody,
  DialogFooter,
  DialogLoading,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Loader2 } from 'lucide-react';
import type { ChannelTypeOption } from '../types';
import { ConfigFormFactory } from './config-forms/ConfigFormFactory';
import { useNotificationChannelForm } from './hooks/useNotificationChannelForm';

interface NotificationChannelDialogProps {
  open: boolean;
  editId?: number;
  channelTypes: ChannelTypeOption[];
  onOpenChange: (open: boolean) => void;
  onSuccess: () => void;
}

const NotificationChannelDialog: React.FC<NotificationChannelDialogProps> = ({
  open,
  editId,
  channelTypes,
  onOpenChange,
  onSuccess,
}) => {
  const {
    // 状态
    loading,
    saving,
    selectedType,
    configState,
    mode,
    
    // 表单
    register,
    handleSubmit,
    errors,
    isValid,
    setValue,
    
    // 方法
    onSubmit,
    updateConfigState,
  } = useNotificationChannelForm({
    open,
    editId,
    onSuccess,
    onOpenChange,
  });

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>
            {mode === 'edit' ? '编辑' : '创建'}通知渠道
          </DialogTitle>
        </DialogHeader>

        <DialogBody>
          {loading ? (
            <DialogLoading />
          ) : (
            <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
              {/* 基础信息 */}
              <BasicInfoSection 
                register={register}
                errors={errors}
                selectedType={selectedType}
                channelTypes={channelTypes}
                mode={mode}
                onTypeChange={(type) => setValue('channelType', type)}
              />

              {/* 配置表单 */}
              <ConfigSection
                selectedType={selectedType}
                register={register}
                errors={errors}
                setValue={setValue}
                configState={configState}
                updateConfigState={updateConfigState}
              />

              {/* 描述 */}
              <DescriptionSection 
                register={register}
                errors={errors}
              />
            </form>
          )}
        </DialogBody>
        
        {!loading && (
          <DialogFooter>
            <Button variant="outline" type="button" onClick={() => onOpenChange(false)}>
              取消
            </Button>
            <Button 
              type="button" 
              disabled={saving || !isValid}
              onClick={handleSubmit(onSubmit)}
              title={!isValid ? `表单验证失败: ${Object.keys(errors).join(', ')}` : ''}
            >
              {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {mode === 'edit' ? '保存' : '创建'}
            </Button>
          </DialogFooter>
        )}
      </DialogContent>
    </Dialog>
  );
};

// 基础信息组件
interface BasicInfoSectionProps {
  register: any;
  errors: any;
  selectedType: any;
  channelTypes: ChannelTypeOption[];
  mode: string;
  onTypeChange: (type: any) => void;
}

const BasicInfoSection: React.FC<BasicInfoSectionProps> = ({
  register,
  errors,
  selectedType,
  channelTypes,
  mode,
  onTypeChange,
}) => (
  <>
    {/* 渠道名称 */}
    <div className="space-y-2">
      <Label htmlFor="name">
        渠道名称 <span className="text-destructive">*</span>
      </Label>
      <Input
        id="name"
        placeholder="例如：研发部企业微信群"
        {...register('name')}
      />
      {errors.name && (
        <p className="text-sm text-destructive">{errors.name.message}</p>
      )}
    </div>

    {/* 渠道类型 */}
    <div className="space-y-2">
      <Label htmlFor="channelType">
        渠道类型 <span className="text-destructive">*</span>
      </Label>
      <Select
        value={selectedType}
        onValueChange={onTypeChange}
        disabled={mode === 'edit'}
      >
        <SelectTrigger>
          <SelectValue placeholder="请选择渠道类型" />
        </SelectTrigger>
        <SelectContent>
          {channelTypes.length === 0 ? (
            <div className="p-4 text-center text-sm text-muted-foreground">
              暂无渠道类型
            </div>
          ) : (
            channelTypes.map((type) => (
              <SelectItem key={type.code} value={type.code}>
                {type.label}
              </SelectItem>
            ))
          )}
        </SelectContent>
      </Select>
      {mode === 'edit' && (
        <p className="text-xs text-muted-foreground">
          编辑时不可修改渠道类型
        </p>
      )}
      {errors.channelType && (
        <p className="text-sm text-destructive">{errors.channelType.message}</p>
      )}
    </div>
  </>
);

// 配置表单组件
interface ConfigSectionProps {
  selectedType: any;
  register: any;
  errors: any;
  setValue: any;
  configState: any;
  updateConfigState: any;
}

const ConfigSection: React.FC<ConfigSectionProps> = ({
  selectedType,
  register,
  errors,
  setValue,
  configState,
  updateConfigState,
}) => {
  const configForm = ConfigFormFactory.createConfigForm(selectedType, {
    register,
    errors,
    setValue,
    configState,
    updateConfigState,
  });

  return configForm ? <div className="space-y-4">{configForm}</div> : null;
};

// 描述组件
interface DescriptionSectionProps {
  register: any;
  errors: any;
}

const DescriptionSection: React.FC<DescriptionSectionProps> = ({
  register,
  errors,
}) => (
  <div className="space-y-2">
    <Label htmlFor="description">描述（可选）</Label>
    <Textarea
      id="description"
      rows={3}
      placeholder="渠道用途说明"
      {...register('description')}
    />
    {errors.description && (
      <p className="text-sm text-destructive">{errors.description.message}</p>
    )}
  </div>
);

export { NotificationChannelDialog };
export default NotificationChannelDialog;
