import { X, Save, Trash2, ShieldCheck, Info, Package, Truck, User, Calendar, FileText, CheckCircle, XCircle } from 'lucide-react';
import { clsx } from 'clsx';
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 p-4 bg-black/60 backdrop-blur-sm animate-fade-in" onClick={onClose}>
      <div className="glass-effect rounded-3xl w-full max-w-3xl max-h-[90vh] overflow-hidden flex flex-col shadow-2xl border border-white/10 animate-scale-in" onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div className="px-8 py-6 border-b border-white/10 flex items-center justify-between bg-white/5">
          <div className="flex items-center gap-4">
            <div className="p-2.5 bg-primary-500/20 rounded-xl">
              <ShieldCheck className="w-6 h-6 text-primary-400" />
            </div>
            <div>
              <h2 className="text-xl font-bold text-white leading-tight">
                {formData.idx ? '라이선스 수정' : '라이선스 추가'}
              </h2>
              <p className="text-xs text-white/40 uppercase tracking-widest font-medium mt-0.5">Edit License Details</p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-white/30 hover:text-white hover:bg-white/10 rounded-xl transition-all"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto custom-scrollbar p-8 space-y-8">
          {/* 기본 정보 */}
          <div className="space-y-4">
            <h3 className="text-sm font-bold text-primary-400 flex items-center gap-2 uppercase tracking-widest py-1 border-b border-white/5 mb-4">
              <Info className="w-4 h-4" />
              기본 정보
            </h3>
            <div className="grid grid-cols-12 gap-5">
              <div className="col-span-12 md:col-span-2">
                <label className="block text-xs font-bold text-white/30 uppercase tracking-widest mb-2 px-1">상태</label>
                <button
                  type="button"
                  onClick={() => setFormData({ ...formData, expire: !formData.expire })}
                  className={clsx(
                    "w-full px-4 py-2.5 rounded-xl border transition-all flex items-center justify-center gap-2 font-bold text-sm",
                    formData.expire
                      ? "bg-danger-500/20 border-danger-500/30 text-danger-400"
                      : "bg-success-500/20 border-success-500/30 text-success-400"
                  )}
                >
                  {formData.expire ? (
                    <><XCircle className="w-4 h-4" /> 만료</>
                  ) : (
                    <><CheckCircle className="w-4 h-4" /> 유효</>
                  )}
                </button>
              </div>
              <div className="col-span-12 md:col-span-5">
                <label className="block text-xs font-bold text-white/30 uppercase tracking-widest mb-2 px-1">제품명 *</label>
                <div className="relative group">
                  <Package className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-white/20 group-focus-within:text-primary-400 transition-colors" />
                  <input
                    type="text"
                    value={formData.name || ''}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    className="w-full pl-10 pr-4 py-2.5 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/20 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all font-medium"
                    placeholder="제품명을 입력하세요"
                  />
                </div>
              </div>
              <div className="col-span-12 md:col-span-2">
                <label className="block text-xs font-bold text-white/30 uppercase tracking-widest mb-2 px-1">버전</label>
                <input
                  type="text"
                  value={formData.version || ''}
                  onChange={(e) => setFormData({ ...formData, version: e.target.value })}
                  className="w-full px-4 py-2.5 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/20 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all font-medium"
                  placeholder="v1.0"
                />
              </div>
              <div className="col-span-12 md:col-span-3">
                <label className="block text-xs font-bold text-white/30 uppercase tracking-widest mb-2 px-1">자재번호</label>
                <input
                  type="text"
                  value={formData.meterialNo || ''}
                  onChange={(e) => setFormData({ ...formData, meterialNo: e.target.value })}
                  className="w-full px-4 py-2.5 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/20 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all font-medium font-mono"
                  placeholder="M-0000"
                />
              </div>
            </div>
          </div>

          {/* 공급 정보 */}
          <div className="space-y-4">
            <h3 className="text-sm font-bold text-primary-400 flex items-center gap-2 uppercase tracking-widest py-1 border-b border-white/5 mb-4">
              <Truck className="w-4 h-4" />
              공급 정보
            </h3>
            <div className="grid grid-cols-2 gap-5">
              <div>
                <label className="block text-xs font-bold text-white/30 uppercase tracking-widest mb-2 px-1">공급업체</label>
                <input
                  type="text"
                  value={formData.supply || ''}
                  onChange={(e) => setFormData({ ...formData, supply: e.target.value })}
                  className="w-full px-4 py-2.5 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/20 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all font-medium"
                />
              </div>
              <div>
                <label className="block text-xs font-bold text-white/30 uppercase tracking-widest mb-2 px-1">제조사</label>
                <input
                  type="text"
                  value={formData.manu || ''}
                  onChange={(e) => setFormData({ ...formData, manu: e.target.value })}
                  className="w-full px-4 py-2.5 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/20 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all font-medium"
                />
              </div>
            </div>
          </div>

          {/* 사용 정보 */}
          <div className="space-y-4">
            <h3 className="text-sm font-bold text-primary-400 flex items-center gap-2 uppercase tracking-widest py-1 border-b border-white/5 mb-4">
              <User className="w-4 h-4" />
              사용 정보
            </h3>
            <div className="grid grid-cols-12 gap-5">
              <div className="col-span-12 md:col-span-2">
                <label className="block text-xs font-bold text-white/30 uppercase tracking-widest mb-2 px-1">수량</label>
                <input
                  type="number"
                  value={formData.qty || 1}
                  onChange={(e) => setFormData({ ...formData, qty: parseInt(e.target.value) || 1 })}
                  className="w-full px-4 py-2.5 bg-white/5 border border-white/10 rounded-xl text-white focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all font-bold text-center"
                />
              </div>
              <div className="col-span-12 md:col-span-4">
                <label className="block text-xs font-bold text-white/30 uppercase tracking-widest mb-2 px-1">사용자</label>
                <input
                  type="text"
                  value={formData.uids || ''}
                  onChange={(e) => setFormData({ ...formData, uids: e.target.value })}
                  className="w-full px-4 py-2.5 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/20 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all font-medium"
                />
              </div>
              <div className="col-span-12 md:col-span-6">
                <label className="block text-xs font-bold text-white/30 uppercase tracking-widest mb-2 px-1">S/N</label>
                <input
                  type="text"
                  value={formData.serialNo || ''}
                  onChange={(e) => setFormData({ ...formData, serialNo: e.target.value })}
                  className="w-full px-4 py-2.5 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/20 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all font-medium font-mono"
                />
              </div>
            </div>
          </div>

          {/* 기간 정보 */}
          <div className="space-y-4">
            <h3 className="text-sm font-bold text-primary-400 flex items-center gap-2 uppercase tracking-widest py-1 border-b border-white/5 mb-4">
              <Calendar className="w-4 h-4" />
              기간 정보
            </h3>
            <div className="grid grid-cols-2 gap-5">
              <div>
                <label className="block text-xs font-bold text-white/30 uppercase tracking-widest mb-2 px-1">시작일</label>
                <div className="relative group">
                  <Calendar className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-white/20 group-focus-within:text-primary-400 transition-colors pointer-events-none" />
                  <input
                    type="date"
                    value={formData.sdate || ''}
                    onChange={(e) => setFormData({ ...formData, sdate: e.target.value })}
                    className="w-full pl-10 pr-4 py-2.5 bg-white/5 border border-white/10 rounded-xl text-white focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all font-medium custom-calendar-icon"
                  />
                </div>
              </div>
              <div>
                <label className="block text-xs font-bold text-white/30 uppercase tracking-widest mb-2 px-1">종료일</label>
                <div className="relative group">
                  <Calendar className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-white/20 group-focus-within:text-primary-400 transition-colors pointer-events-none" />
                  <input
                    type="date"
                    value={formData.edate || ''}
                    onChange={(e) => setFormData({ ...formData, edate: e.target.value })}
                    className="w-full pl-10 pr-4 py-2.5 bg-white/5 border border-white/10 rounded-xl text-white focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all font-medium custom-calendar-icon"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* 비고 */}
          <div className="space-y-4">
            <h3 className="text-sm font-bold text-primary-400 flex items-center gap-2 uppercase tracking-widest py-1 border-b border-white/5 mb-4">
              <FileText className="w-4 h-4" />
              비고
            </h3>
            <textarea
              value={formData.remark || ''}
              onChange={(e) => setFormData({ ...formData, remark: e.target.value })}
              rows={4}
              className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-2xl text-white placeholder-white/20 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all font-medium resize-none"
              placeholder="추가 메모를 입력하세요..."
            />
          </div>
        </div>

        {/* Footer */}
        <div className="px-8 py-6 border-t border-white/10 flex items-center justify-between bg-white/5">
          <div>
            {formData.idx && onDelete && (
              <button
                onClick={handleDelete}
                disabled={saving}
                className="flex items-center gap-2 px-5 py-2.5 bg-danger-500/10 hover:bg-danger-500/20 text-danger-400 border border-danger-500/20 rounded-xl transition-all font-bold group active:scale-95"
              >
                <Trash2 className="w-4 h-4 group-hover:shake" />
                <span>삭제</span>
              </button>
            )}
          </div>
          <div className="flex items-center gap-3">
            <button
              onClick={onClose}
              disabled={saving}
              className="px-6 py-2.5 bg-white/5 hover:bg-white/10 text-white/70 hover:text-white border border-white/10 rounded-xl transition-all font-bold active:scale-95"
            >
              취소
            </button>
            <button
              onClick={handleSave}
              disabled={saving}
              className="flex items-center gap-2 px-8 py-2.5 bg-primary-500 hover:bg-primary-600 text-white border border-primary-500/20 rounded-xl transition-all font-bold shadow-lg shadow-primary-500/20 active:scale-95 disabled:opacity-50"
            >
              <Save className={clsx("w-4 h-4", saving && "animate-spin")} />
              <span>{saving ? '저장 중...' : '저장'}</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
