import React, { useState, useEffect } from 'react';
import { Model, Gender, CreateModelRequest, UpdateModelRequest, ModelFormErrors } from '../types/model';
import { XMarkIcon } from '@heroicons/react/24/outline';

interface ModelFormProps {
  initialData?: Model;
  onSubmit: (data: CreateModelRequest | UpdateModelRequest) => void;
  onCancel: () => void;
  isEdit?: boolean;
}

const ModelForm: React.FC<ModelFormProps> = ({
  initialData,
  onSubmit,
  onCancel,
  isEdit = false
}) => {
  const [formData, setFormData] = useState({
    name: '',
    stage_name: '',
    gender: Gender.Female,
    age: '',
    height: '',
    weight: '',
    description: '',
    tags: [] as string[],
    measurements: {
      bust: '',
      waist: '',
      hips: ''
    },
    contact_info: {
      phone: '',
      email: '',
      wechat: '',
      qq: '',
      address: ''
    },
    social_media: {
      weibo: '',
      instagram: '',
      tiktok: '',
      xiaohongshu: '',
      douyin: ''
    }
  });

  const [errors, setErrors] = useState<ModelFormErrors>({});
  const [tagInput, setTagInput] = useState('');

  useEffect(() => {
    if (initialData) {
      setFormData({
        name: initialData.name,
        stage_name: initialData.stage_name || '',
        gender: initialData.gender,
        age: initialData.age?.toString() || '',
        height: initialData.height?.toString() || '',
        weight: initialData.weight?.toString() || '',
        description: initialData.description || '',
        tags: [...initialData.tags],
        measurements: {
          bust: initialData.measurements?.bust?.toString() || '',
          waist: initialData.measurements?.waist?.toString() || '',
          hips: initialData.measurements?.hips?.toString() || ''
        },
        contact_info: {
          phone: initialData.contact_info?.phone || '',
          email: initialData.contact_info?.email || '',
          wechat: initialData.contact_info?.wechat || '',
          qq: initialData.contact_info?.qq || '',
          address: initialData.contact_info?.address || ''
        },
        social_media: {
          weibo: initialData.social_media?.weibo || '',
          instagram: initialData.social_media?.instagram || '',
          tiktok: initialData.social_media?.tiktok || '',
          xiaohongshu: initialData.social_media?.xiaohongshu || '',
          douyin: initialData.social_media?.douyin || ''
        }
      });
    }
  }, [initialData]);

  const validateForm = (): boolean => {
    const newErrors: ModelFormErrors = {};

    if (!formData.name.trim()) {
      newErrors.name = '姓名不能为空';
    } else if (formData.name.length > 50) {
      newErrors.name = '姓名不能超过50个字符';
    }

    if (formData.stage_name && formData.stage_name.length > 50) {
      newErrors.stage_name = '艺名不能超过50个字符';
    }

    if (formData.age && (isNaN(Number(formData.age)) || Number(formData.age) < 0 || Number(formData.age) > 100)) {
      newErrors.age = '年龄必须是0-100之间的数字';
    }

    if (formData.height && (isNaN(Number(formData.height)) || Number(formData.height) < 50 || Number(formData.height) > 250)) {
      newErrors.height = '身高必须是50-250厘米之间的数字';
    }

    if (formData.weight && (isNaN(Number(formData.weight)) || Number(formData.weight) < 20 || Number(formData.weight) > 200)) {
      newErrors.weight = '体重必须是20-200公斤之间的数字';
    }

    if (formData.description && formData.description.length > 1000) {
      newErrors.description = '描述不能超过1000个字符';
    }

    // 验证邮箱格式
    if (formData.contact_info.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.contact_info.email)) {
      newErrors.contact_info = { ...newErrors.contact_info, email: '邮箱格式不正确' };
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    const submitData: any = {
      name: formData.name.trim(),
      gender: formData.gender,
    };

    if (formData.stage_name.trim()) {
      submitData.stage_name = formData.stage_name.trim();
    }

    if (formData.age) {
      submitData.age = Number(formData.age);
    }

    if (formData.height) {
      submitData.height = Number(formData.height);
    }

    if (formData.weight) {
      submitData.weight = Number(formData.weight);
    }

    if (formData.description.trim()) {
      submitData.description = formData.description.trim();
    }

    if (formData.tags.length > 0) {
      submitData.tags = formData.tags;
    }

    // 三围信息
    if (formData.measurements.bust || formData.measurements.waist || formData.measurements.hips) {
      submitData.measurements = {
        bust: Number(formData.measurements.bust) || 0,
        waist: Number(formData.measurements.waist) || 0,
        hips: Number(formData.measurements.hips) || 0
      };
    }

    // 联系信息
    const hasContactInfo = Object.values(formData.contact_info).some(value => value.trim());
    if (hasContactInfo) {
      submitData.contact_info = Object.fromEntries(
        Object.entries(formData.contact_info).filter(([_, value]) => value.trim())
      );
    }

    // 社交媒体信息
    const hasSocialMedia = Object.values(formData.social_media).some(value => value.trim());
    if (hasSocialMedia) {
      submitData.social_media = Object.fromEntries(
        Object.entries(formData.social_media).filter(([_, value]) => value.trim())
      );
    }

    onSubmit(submitData);
  };

  const addTag = () => {
    const tag = tagInput.trim();
    if (tag && !formData.tags.includes(tag)) {
      setFormData(prev => ({
        ...prev,
        tags: [...prev.tags, tag]
      }));
      setTagInput('');
    }
  };

  const removeTag = (tagToRemove: string) => {
    setFormData(prev => ({
      ...prev,
      tags: prev.tags.filter(tag => tag !== tagToRemove)
    }));
  };

  const handleTagKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      addTag();
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 className="text-xl font-semibold text-gray-900">
            {isEdit ? '编辑模特' : '添加模特'}
          </h2>
          <button
            onClick={onCancel}
            className="text-gray-400 hover:text-gray-600"
          >
            <XMarkIcon className="h-6 w-6" />
          </button>
        </div>

        {/* 表单内容 */}
        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          {/* 基本信息 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                姓名 <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${
                  errors.name ? 'border-red-500' : 'border-gray-300'
                }`}
                placeholder="请输入姓名"
              />
              {errors.name && <p className="mt-1 text-sm text-red-600">{errors.name}</p>}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                艺名
              </label>
              <input
                type="text"
                value={formData.stage_name}
                onChange={(e) => setFormData(prev => ({ ...prev, stage_name: e.target.value }))}
                className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${
                  errors.stage_name ? 'border-red-500' : 'border-gray-300'
                }`}
                placeholder="请输入艺名"
              />
              {errors.stage_name && <p className="mt-1 text-sm text-red-600">{errors.stage_name}</p>}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                性别 <span className="text-red-500">*</span>
              </label>
              <select
                value={formData.gender}
                onChange={(e) => setFormData(prev => ({ ...prev, gender: e.target.value as Gender }))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value={Gender.Female}>女</option>
                <option value={Gender.Male}>男</option>
                <option value={Gender.Other}>其他</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                年龄
              </label>
              <input
                type="number"
                value={formData.age}
                onChange={(e) => setFormData(prev => ({ ...prev, age: e.target.value }))}
                className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${
                  errors.age ? 'border-red-500' : 'border-gray-300'
                }`}
                placeholder="请输入年龄"
                min="0"
                max="100"
              />
              {errors.age && <p className="mt-1 text-sm text-red-600">{errors.age}</p>}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                身高 (cm)
              </label>
              <input
                type="number"
                value={formData.height}
                onChange={(e) => setFormData(prev => ({ ...prev, height: e.target.value }))}
                className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${
                  errors.height ? 'border-red-500' : 'border-gray-300'
                }`}
                placeholder="请输入身高"
                min="50"
                max="250"
              />
              {errors.height && <p className="mt-1 text-sm text-red-600">{errors.height}</p>}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                体重 (kg)
              </label>
              <input
                type="number"
                value={formData.weight}
                onChange={(e) => setFormData(prev => ({ ...prev, weight: e.target.value }))}
                className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${
                  errors.weight ? 'border-red-500' : 'border-gray-300'
                }`}
                placeholder="请输入体重"
                min="20"
                max="200"
              />
              {errors.weight && <p className="mt-1 text-sm text-red-600">{errors.weight}</p>}
            </div>
          </div>

          {/* 描述 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              描述
            </label>
            <textarea
              value={formData.description}
              onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
              rows={3}
              className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${
                errors.description ? 'border-red-500' : 'border-gray-300'
              }`}
              placeholder="请输入描述信息"
            />
            {errors.description && <p className="mt-1 text-sm text-red-600">{errors.description}</p>}
          </div>

          {/* 标签 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              标签
            </label>
            <div className="flex gap-2 mb-2">
              <input
                type="text"
                value={tagInput}
                onChange={(e) => setTagInput(e.target.value)}
                onKeyPress={handleTagKeyPress}
                className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="输入标签后按回车添加"
              />
              <button
                type="button"
                onClick={addTag}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                添加
              </button>
            </div>
            {formData.tags.length > 0 && (
              <div className="flex flex-wrap gap-2">
                {formData.tags.map((tag, index) => (
                  <span
                    key={index}
                    className="inline-flex items-center gap-1 px-3 py-1 bg-blue-100 text-blue-800 text-sm rounded-full"
                  >
                    {tag}
                    <button
                      type="button"
                      onClick={() => removeTag(tag)}
                      className="text-blue-600 hover:text-blue-800"
                    >
                      ×
                    </button>
                  </span>
                ))}
              </div>
            )}
          </div>

          {/* 操作按钮 */}
          <div className="flex justify-end gap-3 pt-6 border-t border-gray-200">
            <button
              type="button"
              onClick={onCancel}
              className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200"
            >
              取消
            </button>
            <button
              type="submit"
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
            >
              {isEdit ? '更新' : '创建'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default ModelForm;
