import { useState, useEffect, useCallback } from 'react';
import {
  Mail,
  Plus,
  Edit2,
  Trash2,
  Save,
  X,
  Loader2,
  RefreshCw,
  Search,
} from 'lucide-react';
import { comms } from '@/communication';
import { MailFormItem } from '@/types';

const initialFormData: Partial<MailFormItem> = {
  cate: '',
  title: '',
  tolist: '',
  bcc: '',
  cc: '',
  subject: '',
  tail: '',
  body: '',
  selfTo: false,
  selfCC: false,
  selfBCC: false,
  exceptmail: '',
  exceptmailcc: '',
};

export function MailFormPage() {
  const [loading, setLoading] = useState(false);
  const [mailForms, setMailForms] = useState<MailFormItem[]>([]);
  const [searchKey, setSearchKey] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingItem, setEditingItem] = useState<MailFormItem | null>(null);
  const [formData, setFormData] = useState<Partial<MailFormItem>>(initialFormData);
  const [saving, setSaving] = useState(false);

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const response = await comms.getMailFormList();
      if (response.Success && response.Data) {
        setMailForms(response.Data);
      }
    } catch (error) {
      console.error('데이터 로드 오류:', error);
      alert('데이터를 불러오는 중 오류가 발생했습니다.');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadData();
  }, [loadData]);

  const filteredItems = mailForms.filter(item =>
    !searchKey ||
    item.title?.toLowerCase().includes(searchKey.toLowerCase()) ||
    item.cate?.toLowerCase().includes(searchKey.toLowerCase()) ||
    item.subject?.toLowerCase().includes(searchKey.toLowerCase())
  );

  const openAddModal = () => {
    setEditingItem(null);
    setFormData(initialFormData);
    setShowModal(true);
  };

  const openEditModal = (item: MailFormItem) => {
    setEditingItem(item);
    setFormData({
      cate: item.cate || '',
      title: item.title || '',
      tolist: item.tolist || '',
      bcc: item.bcc || '',
      cc: item.cc || '',
      subject: item.subject || '',
      tail: item.tail || '',
      body: item.body || '',
      selfTo: item.selfTo || false,
      selfCC: item.selfCC || false,
      selfBCC: item.selfBCC || false,
      exceptmail: item.exceptmail || '',
      exceptmailcc: item.exceptmailcc || '',
    });
    setShowModal(true);
  };

  const handleSave = async () => {
    if (!formData.title?.trim()) {
      alert('양식명을 입력해주세요.');
      return;
    }

    setSaving(true);
    try {
      let response;
      if (editingItem) {
        response = await comms.editMailForm(
          editingItem.idx,
          formData.cate || '',
          formData.title || '',
          formData.tolist || '',
          formData.bcc || '',
          formData.cc || '',
          formData.subject || '',
          formData.tail || '',
          formData.body || '',
          formData.selfTo || false,
          formData.selfCC || false,
          formData.selfBCC || false,
          formData.exceptmail || '',
          formData.exceptmailcc || ''
        );
      } else {
        response = await comms.addMailForm(
          formData.cate || '',
          formData.title || '',
          formData.tolist || '',
          formData.bcc || '',
          formData.cc || '',
          formData.subject || '',
          formData.tail || '',
          formData.body || '',
          formData.selfTo || false,
          formData.selfCC || false,
          formData.selfBCC || false,
          formData.exceptmail || '',
          formData.exceptmailcc || ''
        );
      }

      if (response.Success) {
        setShowModal(false);
        loadData();
      } else {
        alert(response.Message || '저장에 실패했습니다.');
      }
    } catch (error) {
      console.error('저장 오류:', error);
      alert('저장 중 오류가 발생했습니다.');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (item: MailFormItem) => {
    if (!confirm(`"${item.title}" 양식을 삭제하시겠습니까?`)) return;

    try {
      const response = await comms.deleteMailForm(item.idx);
      if (response.Success) {
        loadData();
      } else {
        alert(response.Message || '삭제에 실패했습니다.');
      }
    } catch (error) {
      console.error('삭제 오류:', error);
      alert('삭제 중 오류가 발생했습니다.');
    }
  };

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="glass-effect rounded-2xl p-6">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div className="flex items-center space-x-3">
            <div className="p-3 bg-primary-500/20 rounded-xl">
              <Mail className="w-6 h-6 text-primary-400" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-white">메일양식</h1>
              <p className="text-white/60 text-sm">메일 템플릿 관리</p>
            </div>
          </div>

          <div className="flex items-center space-x-3">
            {/* 검색 */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-white/40" />
              <input
                type="text"
                value={searchKey}
                onChange={(e) => setSearchKey(e.target.value)}
                placeholder="검색..."
                className="pl-10 pr-4 py-2 bg-white/10 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-primary-500 w-48"
              />
            </div>

            <button
              onClick={loadData}
              disabled={loading}
              className="flex items-center space-x-2 px-4 py-2 bg-white/10 hover:bg-white/20 rounded-lg text-white transition-colors disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
            </button>

            <button
              onClick={openAddModal}
              className="flex items-center space-x-2 px-4 py-2 bg-primary-500 hover:bg-primary-600 rounded-lg text-white transition-colors"
            >
              <Plus className="w-4 h-4" />
              <span>새 양식</span>
            </button>
          </div>
        </div>
      </div>

      {/* 목록 */}
      <div className="glass-effect rounded-2xl overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center py-20">
            <Loader2 className="w-8 h-8 text-white animate-spin" />
          </div>
        ) : filteredItems.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 text-white/50">
            <Mail className="w-12 h-12 mb-4 opacity-50" />
            <p>등록된 메일양식이 없습니다.</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-white/10">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-white/70 uppercase w-24">분류</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-white/70 uppercase">양식명</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-white/70 uppercase">제목</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-white/70 uppercase w-20">To</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-white/70 uppercase w-20">CC</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-white/70 uppercase w-20">BCC</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-white/70 uppercase w-24">작업</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-white/5">
                {filteredItems.map((item) => (
                  <tr key={item.idx} className="hover:bg-white/5 transition-colors">
                    <td className="px-4 py-3 text-white/70 text-sm">{item.cate || '-'}</td>
                    <td className="px-4 py-3 text-white text-sm font-medium">{item.title}</td>
                    <td className="px-4 py-3 text-white/70 text-sm">{item.subject || '-'}</td>
                    <td className="px-4 py-3 text-center">
                      {item.selfTo && (
                        <span className="inline-block w-5 h-5 bg-success-500/20 text-success-400 rounded text-xs leading-5">S</span>
                      )}
                    </td>
                    <td className="px-4 py-3 text-center">
                      {item.selfCC && (
                        <span className="inline-block w-5 h-5 bg-warning-500/20 text-warning-400 rounded text-xs leading-5">S</span>
                      )}
                    </td>
                    <td className="px-4 py-3 text-center">
                      {item.selfBCC && (
                        <span className="inline-block w-5 h-5 bg-primary-500/20 text-primary-400 rounded text-xs leading-5">S</span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-center space-x-2">
                        <button
                          onClick={() => openEditModal(item)}
                          className="p-1.5 hover:bg-white/10 rounded text-white/70 hover:text-white transition-colors"
                          title="수정"
                        >
                          <Edit2 className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleDelete(item)}
                          className="p-1.5 hover:bg-danger-500/20 rounded text-white/70 hover:text-danger-400 transition-colors"
                          title="삭제"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* 편집 모달 */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="bg-slate-800 rounded-2xl w-full max-w-4xl max-h-[90vh] overflow-hidden flex flex-col">
            {/* 모달 헤더 */}
            <div className="flex items-center justify-between px-6 py-4 border-b border-white/10">
              <h2 className="text-xl font-bold text-white">
                {editingItem ? '메일양식 수정' : '새 메일양식'}
              </h2>
              <button
                onClick={() => setShowModal(false)}
                className="p-2 hover:bg-white/10 rounded-lg text-white/70 hover:text-white transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* 모달 내용 */}
            <div className="flex-1 overflow-y-auto p-6 space-y-4">
              {/* 1행: 분류, 양식명 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-white/70 text-sm mb-1">분류</label>
                  <input
                    type="text"
                    value={formData.cate || ''}
                    onChange={(e) => setFormData({ ...formData, cate: e.target.value })}
                    className="w-full px-3 py-2 bg-white/10 border border-white/10 rounded-lg text-white focus:outline-none focus:border-primary-500"
                  />
                </div>
                <div>
                  <label className="block text-white/70 text-sm mb-1">양식명 *</label>
                  <input
                    type="text"
                    value={formData.title || ''}
                    onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                    className="w-full px-3 py-2 bg-white/10 border border-white/10 rounded-lg text-white focus:outline-none focus:border-primary-500"
                  />
                </div>
              </div>

              {/* 2행: 제목 */}
              <div>
                <label className="block text-white/70 text-sm mb-1">메일 제목</label>
                <input
                  type="text"
                  value={formData.subject || ''}
                  onChange={(e) => setFormData({ ...formData, subject: e.target.value })}
                  className="w-full px-3 py-2 bg-white/10 border border-white/10 rounded-lg text-white focus:outline-none focus:border-primary-500"
                />
              </div>

              {/* 3행: 수신자 */}
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-white/70 text-sm mb-1">To (수신)</label>
                  <textarea
                    value={formData.tolist || ''}
                    onChange={(e) => setFormData({ ...formData, tolist: e.target.value })}
                    rows={2}
                    className="w-full px-3 py-2 bg-white/10 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-primary-500 resize-none"
                    placeholder="이메일 주소 (줄바꿈으로 구분)"
                  />
                  <label className="flex items-center mt-1 text-sm text-white/60">
                    <input
                      type="checkbox"
                      checked={formData.selfTo || false}
                      onChange={(e) => setFormData({ ...formData, selfTo: e.target.checked })}
                      className="mr-2"
                    />
                    본인 포함
                  </label>
                </div>
                <div>
                  <label className="block text-white/70 text-sm mb-1">CC (참조)</label>
                  <textarea
                    value={formData.cc || ''}
                    onChange={(e) => setFormData({ ...formData, cc: e.target.value })}
                    rows={2}
                    className="w-full px-3 py-2 bg-white/10 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-primary-500 resize-none"
                    placeholder="이메일 주소 (줄바꿈으로 구분)"
                  />
                  <label className="flex items-center mt-1 text-sm text-white/60">
                    <input
                      type="checkbox"
                      checked={formData.selfCC || false}
                      onChange={(e) => setFormData({ ...formData, selfCC: e.target.checked })}
                      className="mr-2"
                    />
                    본인 포함
                  </label>
                </div>
                <div>
                  <label className="block text-white/70 text-sm mb-1">BCC (숨은참조)</label>
                  <textarea
                    value={formData.bcc || ''}
                    onChange={(e) => setFormData({ ...formData, bcc: e.target.value })}
                    rows={2}
                    className="w-full px-3 py-2 bg-white/10 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-primary-500 resize-none"
                    placeholder="이메일 주소 (줄바꿈으로 구분)"
                  />
                  <label className="flex items-center mt-1 text-sm text-white/60">
                    <input
                      type="checkbox"
                      checked={formData.selfBCC || false}
                      onChange={(e) => setFormData({ ...formData, selfBCC: e.target.checked })}
                      className="mr-2"
                    />
                    본인 포함
                  </label>
                </div>
              </div>

              {/* 4행: 제외 메일 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-white/70 text-sm mb-1">To 제외 메일</label>
                  <input
                    type="text"
                    value={formData.exceptmail || ''}
                    onChange={(e) => setFormData({ ...formData, exceptmail: e.target.value })}
                    className="w-full px-3 py-2 bg-white/10 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-primary-500"
                    placeholder="제외할 이메일 주소"
                  />
                </div>
                <div>
                  <label className="block text-white/70 text-sm mb-1">CC 제외 메일</label>
                  <input
                    type="text"
                    value={formData.exceptmailcc || ''}
                    onChange={(e) => setFormData({ ...formData, exceptmailcc: e.target.value })}
                    className="w-full px-3 py-2 bg-white/10 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-primary-500"
                    placeholder="제외할 이메일 주소"
                  />
                </div>
              </div>

              {/* 5행: 본문 */}
              <div>
                <label className="block text-white/70 text-sm mb-1">메일 본문</label>
                <textarea
                  value={formData.body || ''}
                  onChange={(e) => setFormData({ ...formData, body: e.target.value })}
                  rows={6}
                  className="w-full px-3 py-2 bg-white/10 border border-white/10 rounded-lg text-white focus:outline-none focus:border-primary-500 resize-none"
                  placeholder="메일 본문 내용..."
                />
              </div>

              {/* 6행: 꼬리말 */}
              <div>
                <label className="block text-white/70 text-sm mb-1">꼬리말</label>
                <textarea
                  value={formData.tail || ''}
                  onChange={(e) => setFormData({ ...formData, tail: e.target.value })}
                  rows={3}
                  className="w-full px-3 py-2 bg-white/10 border border-white/10 rounded-lg text-white focus:outline-none focus:border-primary-500 resize-none"
                  placeholder="메일 꼬리말..."
                />
              </div>
            </div>

            {/* 모달 푸터 */}
            <div className="flex items-center justify-end space-x-3 px-6 py-4 border-t border-white/10">
              <button
                onClick={() => setShowModal(false)}
                className="px-4 py-2 bg-white/10 hover:bg-white/20 rounded-lg text-white transition-colors"
              >
                취소
              </button>
              <button
                onClick={handleSave}
                disabled={saving}
                className="flex items-center space-x-2 px-4 py-2 bg-primary-500 hover:bg-primary-600 rounded-lg text-white transition-colors disabled:opacity-50"
              >
                {saving ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Save className="w-4 h-4" />
                )}
                <span>저장</span>
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
