import { useState, useEffect } from 'react';
import { getGroups, createWebsite, updateWebsite } from '../services/api';

export default function WebsiteModal({ isOpen, onClose, onSuccess, editData }) {
  const [formData, setFormData] = useState({
    name: '',
    groups: [],
    urls: [''],
  });
  const [groups, setGroups] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    if (isOpen) {
      loadGroups();
      if (editData) {
        const editGroups = editData.website?.groups
          || (editData.website?.group ? [editData.website.group] : []);
        setFormData({
          name: editData.website?.name || '',
          groups: editGroups,
          urls: editData.website?.urls?.map(u => u.url) || [''],
        });
      } else {
        setFormData({ name: '', groups: [], urls: [''] });
      }
      setError('');
    }
  }, [isOpen, editData]);

  const loadGroups = async () => {
    try {
      const data = await getGroups();
      setGroups(data || []);
    } catch (err) {
      console.error('加载分组失败:', err);
    }
  };

  const handleAddUrl = () => {
    setFormData({ ...formData, urls: [...formData.urls, ''] });
  };

  const handleRemoveUrl = (index) => {
    if (formData.urls.length > 1) {
      const newUrls = formData.urls.filter((_, i) => i !== index);
      setFormData({ ...formData, urls: newUrls });
    }
  };

  const handleUrlChange = (index, value) => {
    const newUrls = [...formData.urls];
    newUrls[index] = value;
    setFormData({ ...formData, urls: newUrls });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    
    // 验证
    if (!formData.name.trim()) {
      setError('请输入网站名称');
      return;
    }
    
    const validUrls = formData.urls.filter(url => url.trim());
    if (validUrls.length === 0) {
      setError('请至少输入一个网站地址');
      return;
    }
    
    // 验证URL格式
    for (const url of validUrls) {
      try {
        new URL(url);
      } catch {
        setError(`无效的URL: ${url}`);
        return;
      }
    }

    if (formData.groups.length === 0) {
      setError('请至少选择一个分组');
      return;
    }

    setLoading(true);
    try {
      const data = {
        name: formData.name.trim(),
        groups: formData.groups,
        urls: validUrls,
      };

      if (editData) {
        await updateWebsite(editData.website.id, data);
      } else {
        await createWebsite(data);
      }
      
      onSuccess?.();
      onClose();
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-md max-h-[90vh] overflow-hidden">
        {/* 标题 */}
        <div className="px-6 py-4 border-b border-gray-100 bg-gradient-to-r from-emerald-50 to-green-50">
          <h2 className="text-lg font-semibold text-gray-800">
            {editData ? '编辑网站' : '添加监控网站'}
          </h2>
        </div>
        
        {/* 表单 */}
        <form onSubmit={handleSubmit} className="p-6 overflow-y-auto max-h-[calc(90vh-140px)]">
          {error && (
            <div className="mb-4 p-3 bg-red-50 border border-red-100 rounded-lg text-sm text-red-600">
              {error}
            </div>
          )}
          
          {/* 网站名称 */}
          <div className="mb-4">
            <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({ ...formData, name: e.target.value })}
              placeholder="例如：我的博客"
              className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent outline-none transition-all"
            />
          </div>
          
          {/* 所属分组（多选） */}
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 mb-1">
              所属分组 <span className="text-xs text-gray-400 font-normal">（可多选）</span>
            </label>
            <div className="flex flex-wrap gap-2 p-3 border border-gray-200 rounded-lg bg-white">
              {groups.map(group => {
                const checked = formData.groups.includes(group.id);
                return (
                  <label
                    key={group.id}
                    className={`inline-flex items-center px-3 py-1.5 rounded-full text-sm cursor-pointer transition-all select-none ${
                      checked
                        ? 'bg-emerald-100 text-emerald-700 ring-1 ring-emerald-300'
                        : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                    }`}
                  >
                    <input
                      type="checkbox"
                      className="sr-only"
                      checked={checked}
                      onChange={() => {
                        const next = checked
                          ? formData.groups.filter(id => id !== group.id)
                          : [...formData.groups, group.id];
                        setFormData({ ...formData, groups: next });
                      }}
                    />
                    {checked && (
                      <svg className="w-3.5 h-3.5 mr-1 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                      </svg>
                    )}
                    {group.name}
                  </label>
                );
              })}
            </div>
          </div>
          
          {/* 网站地址列表 */}
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 mb-1">
              网站地址 <span className="text-red-500">*</span>
            </label>
            <p className="text-xs text-gray-500 mb-2">
              一个网站可以有多个访问地址，将分别监控
            </p>
            
            <div className="space-y-2">
              {formData.urls.map((url, index) => (
                <div key={index} className="flex space-x-2">
                  <input
                    type="text"
                    value={url}
                    onChange={(e) => handleUrlChange(index, e.target.value)}
                    placeholder="https://example.com"
                    className="flex-1 px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent outline-none transition-all"
                  />
                  {formData.urls.length > 1 && (
                    <button
                      type="button"
                      onClick={() => handleRemoveUrl(index)}
                      className="px-3 py-2 text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                    >
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                    </button>
                  )}
                </div>
              ))}
            </div>
            
            <button
              type="button"
              onClick={handleAddUrl}
              className="mt-2 text-sm text-emerald-600 hover:text-emerald-700 flex items-center"
            >
              <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
              </svg>
              添加更多地址
            </button>
          </div>
        </form>
        
        {/* 按钮 */}
        <div className="px-6 py-4 border-t border-gray-100 bg-gray-50 flex justify-end space-x-3">
          <button
            type="button"
            onClick={onClose}
            disabled={loading}
            className="px-4 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
          >
            取消
          </button>
          <button
            onClick={handleSubmit}
            disabled={loading}
            className="px-4 py-2 text-sm font-medium text-white bg-gradient-to-r from-emerald-500 to-green-500 rounded-lg hover:from-emerald-600 hover:to-green-600 transition-all disabled:opacity-50"
          >
            {loading ? '处理中...' : (editData ? '保存' : '添加')}
          </button>
        </div>
      </div>
    </div>
  );
}
