'use client';

import { useState, useEffect } from 'react';
import { MessageTemplate } from '../types';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';

interface MessageTemplateDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  editingTemplate: MessageTemplate | null;
  onSave: (formData: FormData) => void;
}

interface FormData {
  code: string;
  name: string;
  type: 'sms' | 'email' | 'internal' | 'push';
  subject: string;
  content: string;
  variables: string[];
  description: string;
  isActive: boolean;
}

export function MessageTemplateDialog({
  open,
  onOpenChange,
  editingTemplate,
  onSave
}: MessageTemplateDialogProps) {
  const [formData, setFormData] = useState<FormData>({
    code: '',
    name: '',
    type: 'internal',
    subject: '',
    content: '',
    variables: [],
    description: '',
    isActive: true,
  });

  // 使用useEffect来管理表单数据的状态
  useEffect(() => {
    if (editingTemplate) {
      setFormData({
        code: editingTemplate.code,
        name: editingTemplate.name,
        type: editingTemplate.type,
        subject: editingTemplate.subject || '',
        content: editingTemplate.content,
        variables: editingTemplate.variables,
        description: editingTemplate.description || '',
        isActive: editingTemplate.isActive,
      });
    } else if (open) {
      // 新增模式时重置表单
      setFormData({
        code: '',
        name: '',
        type: 'internal',
        subject: '',
        content: '',
        variables: [],
        description: '',
        isActive: true,
      });
    }
  }, [editingTemplate, open]);

  const handleSave = () => {
    onSave(formData);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            {editingTemplate ? '编辑模版' : '新增模版'}
          </DialogTitle>
          <DialogDescription className="sr-only">
            {editingTemplate ? '编辑消息模版' : '添加新消息模版'}
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>模板编码 *</Label>
              <Input
                value={formData.code}
                onChange={(e) => setFormData({ ...formData, code: e.target.value })}
                placeholder="TASK_ASSIGNED"
              />
            </div>
            <div>
              <Label>模板名称 *</Label>
              <Input
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="任务分配通知"
              />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>消息类型 *</Label>
              <Select
                value={formData.type}
                onValueChange={(value: any) => setFormData({ ...formData, type: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="sms">短信</SelectItem>
                  <SelectItem value="email">邮件</SelectItem>
                  <SelectItem value="internal">站内信</SelectItem>
                  <SelectItem value="push">推送</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="flex items-center justify-between pt-6">
              <Label>是否启用</Label>
              <Switch
                checked={formData.isActive}
                onCheckedChange={(checked) => setFormData({ ...formData, isActive: checked })}
              />
            </div>
          </div>
          {(formData.type === 'email' || formData.type === 'push') && (
            <div>
              <Label>消息主题</Label>
              <Input
                value={formData.subject}
                onChange={(e) => setFormData({ ...formData, subject: e.target.value })}
                placeholder="输入消息主题"
              />
            </div>
          )}
          <div>
            <Label>消息内容 *</Label>
            <Textarea
              value={formData.content}
              onChange={(e) => setFormData({ ...formData, content: e.target.value })}
              placeholder="输入消息内容，使用 {{变量名}} 表示变量"
              rows={6}
            />
            <p className="text-xs text-muted-foreground mt-1">
              提示：使用 {'{{'} 和 {'}'} 包裹变量名，如 {'{{username}}'}、{'{{taskName}}'}
            </p>
          </div>
          <div>
            <Label>描述</Label>
            <Textarea
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              placeholder="模板用途说明"
              rows={2}
            />
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleSave}>
            保存
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}