import { X, Save, Trash2 } from 'lucide-react';
import { useState, useEffect } from 'react';
import type { LicenseItem } from '@/types';

interface LicenseEditDialogProps {
  item: LicenseItem | null;
  isOpen: boolean;
  onClose: () => void;
  onSave: (data: Partial<LicenseItem>) => Promise<void>;
  onDelete?: (idx: number) => Promise<void>;
}

export function LicenseEditDialog({ item, isOpen, onClose, onSave, onDelete }: LicenseEditDialogProps) {
  const [formData, setFormData] = useState<Partial<LicenseItem>>({});
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (item) {
      setFormData({
        idx: item.idx,
        expire: item.expire || false,
        name: item.name || '',
        version: item.version || '',
        meterialNo: item.meterialNo || '',
        supply: item.supply || '',
        qty: item.qty || 1,
        uids: item.uids || '',
        serialNo: item.serialNo || '',
        remark: item.remark || '',
        sdate: item.sdate ? item.sdate.split('T')[0] : '',
        edate: item.edate ? item.edate.split('T')[0] : '',
        manu: item.manu || '',
      });
    }
  }, [item]);

  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen) {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener('keydown', handleEscape);
      return () => document.removeEventListener('keydown', handleEscape);
    }
  }, [isOpen, onClose]);

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

    setSaving(true);
    try {
      await onSave(formData);
      onClose();
    } catch (error) {
      console.error('Save failed:', error);
      alert('저장에 실패했습니다.');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!formData.idx) return;
    if (!confirm('삭제하시겠습니까?')) return;

    setSaving(true);
    try {
      if (onDelete) {
        await onDelete(formData.idx);
      }
      onClose();
    } catch (error) {
      console.error('Delete failed:', error);
      alert('삭제에 실패했습니다.');
    } finally {
      setSaving(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={onClose}>
      <div className="glass-effect rounded-lg w-full max-w-3xl max-h-[90vh] overflow-y-auto m-4" onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-white/10">
          <h2 className="text-xl font-semibold text-white">
            {formData.idx ? '라이선스 수정' : '라이선스 추가'}
          </h2>
          <button
            onClick={onClose}
            className="text-white/70 hover:text-white transition-colors"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* Body */}
        <div className="p-6 space-y-6">
          {/* 기본 정보 */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-white/90 flex items-center space-x-2 border-b border-white/10 pb-2">
              <span>기본 정보</span>
            </h3>
            <div className="grid grid-cols-12 gap-4">
              <div className="col-span-1 flex items-center">
                <label className="flex items-center space-x-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={formData.expire || false}
                    onChange={(e) => setFormData({ ...formData, expire: e.target.checked })}
                    className="w-4 h-4"
                  />
                  <span className="text-sm text-white/70">만료</span>
                </label>
              </div>
              <div className="col-span-5">
                <label className="block text-sm text-white/70 mb-1">제품명 *</label>
                <input
                  type="text"
                  value={formData.name || ''}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded text-white focus:outline-none focus:border-blue-500"
                />
              </div>
              <div className="col-span-3">
                <label className="block text-sm text-white/70 mb-1">버전</label>
                <input
                  type="text"
                  value={formData.version || ''}
                  onChange={(e) => setFormData({ ...formData, version: e.target.value })}
                  className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded text-white focus:outline-none focus:border-blue-500"
                />
              </div>
              <div className="col-span-3">
                <label className="block text-sm text-white/70 mb-1">자재번호</label>
                <input
                  type="text"
                  value={formData.meterialNo || ''}
                  onChange={(e) => setFormData({ ...formData, meterialNo: e.target.value })}
                  className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded text-white focus:outline-none focus:border-blue-500"
                />
              </div>
            </div>
          </div>

          {/* 공급 정보 */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-white/90 flex items-center space-x-2 border-b border-white/10 pb-2">
              <span>공급 정보</span>
            </h3>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm text-white/70 mb-1">공급업체</label>
                <input
                  type="text"
                  value={formData.supply || ''}
                  onChange={(e) => setFormData({ ...formData, supply: e.target.value })}
                  className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded text-white focus:outline-none focus:border-blue-500"
                />
              </div>
              <div>
                <label className="block text-sm text-white/70 mb-1">제조사</label>
                <input
                  type="text"
                  value={formData.manu || ''}
                  onChange={(e) => setFormData({ ...formData, manu: e.target.value })}
                  className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded text-white focus:outline-none focus:border-blue-500"
                />
              </div>
            </div>
          </div>

          {/* 사용 정보 */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-white/90 flex items-center space-x-2 border-b border-white/10 pb-2">
              <span>사용 정보</span>
            </h3>
            <div className="grid grid-cols-12 gap-4">
              <div className="col-span-2">
                <label className="block text-sm text-white/70 mb-1">수량</label>
                <input
                  type="number"
                  value={formData.qty || 1}
                  onChange={(e) => setFormData({ ...formData, qty: parseInt(e.target.value) || 1 })}
                  className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded text-white focus:outline-none focus:border-blue-500"
                />
              </div>
              <div className="col-span-4">
                <label className="block text-sm text-white/70 mb-1">사용자</label>
                <input
                  type="text"
                  value={formData.uids || ''}
                  onChange={(e) => setFormData({ ...formData, uids: e.target.value })}
                  className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded text-white focus:outline-none focus:border-blue-500"
                />
              </div>
              <div className="col-span-6">
                <label className="block text-sm text-white/70 mb-1">S/N</label>
                <input
                  type="text"
                  value={formData.serialNo || ''}
                  onChange={(e) => setFormData({ ...formData, serialNo: e.target.value })}
                  className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded text-white focus:outline-none focus:border-blue-500"
                />
              </div>
            </div>
          </div>

          {/* 기간 정보 */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-white/90 flex items-center space-x-2 border-b border-white/10 pb-2">
              <span>기간 정보</span>
            </h3>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm text-white/70 mb-1">시작일</label>
                <input
                  type="date"
                  value={formData.sdate || ''}
                  onChange={(e) => setFormData({ ...formData, sdate: e.target.value })}
                  className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded text-white focus:outline-none focus:border-blue-500"
                />
              </div>
              <div>
                <label className="block text-sm text-white/70 mb-1">종료일</label>
                <input
                  type="date"
                  value={formData.edate || ''}
                  onChange={(e) => setFormData({ ...formData, edate: e.target.value })}
                  className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded text-white focus:outline-none focus:border-blue-500"
                />
              </div>
            </div>
          </div>

          {/* 비고 */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-white/90 flex items-center space-x-2 border-b border-white/10 pb-2">
              <span>비고</span>
            </h3>
            <textarea
              value={formData.remark || ''}
              onChange={(e) => setFormData({ ...formData, remark: e.target.value })}
              rows={3}
              className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded text-white focus:outline-none focus:border-blue-500 resize-none"
              placeholder="추가 메모를 입력하세요..."
            />
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between p-4 border-t border-white/10">
          <div>
            {formData.idx && onDelete && (
              <button
                onClick={handleDelete}
                disabled={saving}
                className="flex items-center space-x-2 px-4 py-2 bg-red-500 hover:bg-red-600 disabled:bg-gray-600 text-white rounded-lg transition-colors"
              >
                <Trash2 className="w-4 h-4" />
                <span>삭제</span>
              </button>
            )}
          </div>
          <div className="flex items-center space-x-2">
            <button
              onClick={onClose}
              disabled={saving}
              className="px-4 py-2 bg-gray-600 hover:bg-gray-700 disabled:bg-gray-800 text-white rounded-lg transition-colors"
            >
              취소
            </button>
            <button
              onClick={handleSave}
              disabled={saving}
              className="flex items-center space-x-2 px-4 py-2 bg-blue-500 hover:bg-blue-600 disabled:bg-gray-600 text-white rounded-lg transition-colors"
            >
              <Save className="w-4 h-4" />
              <span>{saving ? '저장 중...' : '저장'}</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
