import { useState, useEffect, useMemo } from 'react';
import axios from 'axios';
import { Key, Plus, Copy, CheckCircle, Clock, Search, Users, ChevronRight, ArrowLeft, Trash2, LogOut } from 'lucide-react';
import Login from './components/Login';

// Axios settings for cookies
axios.defaults.withCredentials = true;

const API_BASE = import.meta.env.DEV
  ? 'http://localhost:3006/api'
  : '/api';

interface License {
  id: number;
  module_code: string;
  license_key: string;
  license_type: string;
  subscriber_id: string;
  status: string;
  created_at: string;
}

const App = () => {
  const [user, setUser] = useState<any>(null);
  const [authChecked, setAuthChecked] = useState(false);
  const [licenses, setLicenses] = useState<License[]>([]);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [copySuccess, setCopySuccess] = useState<number | null>(null);

  // UI Flow State
  const [currentView, setCurrentView] = useState<'MASTER' | 'DETAIL'>('MASTER');
  const [selectedSubscriber, setSelectedSubscriber] = useState<string>('');
  const [searchQuery, setSearchQuery] = useState<string>('');
  const [appliedSearch, setAppliedSearch] = useState<string>('');

  // Form State
  const [formData, setFormData] = useState({
    moduleCode: 'asset',
    type: 'sub',
    subscriberId: '',
    expiryDate: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
  });

  // Calculate unique subscribers for the master list
  const allSubscribers = useMemo(() => {
    return Array.from(new Set(licenses.map((lic: License) => lic.subscriber_id))).sort();
  }, [licenses]);

  // Filtered subscribers based on applied search
  const filteredSubscribers = useMemo(() => {
    if (!appliedSearch.trim()) return allSubscribers;
    return allSubscribers.filter((sub: string) => sub.toUpperCase().includes(appliedSearch.toUpperCase()));
  }, [allSubscribers, appliedSearch]);

  // Detail view licenses
  const detailLicenses = useMemo(() => {
    return licenses.filter((lic: License) => lic.subscriber_id === selectedSubscriber);
  }, [licenses, selectedSubscriber]);

  const handleSearch = (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    setAppliedSearch(searchQuery);
  };

  const handleManage = (subscriberId: string) => {
    setSelectedSubscriber(subscriberId);
    setCurrentView('DETAIL');
  };

  const handleBack = () => {
    setCurrentView('MASTER');
    setSelectedSubscriber('');
  };

  const handleTypeChange = (type: string) => {
    let days = 365;
    if (type === 'demo') days = 30;
    setFormData({
      ...formData,
      type,
      expiryDate: type === 'dev' ? '' : new Date(Date.now() + days * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
    });
  };

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

  const checkAuth = async () => {
    try {
      const res = await axios.get(`${API_BASE}/auth/me`);
      setUser(res.data);
      fetchLicenses();
    } catch (err) {
      setUser(null);
    } finally {
      setAuthChecked(true);
    }
  };

  const handleLogout = async () => {
    try {
      await axios.post(`${API_BASE}/auth/logout`);
      setUser(null);
    } catch (err) {
      console.error('Logout failed', err);
    }
  };

  useEffect(() => {
    if (user) {
      fetchLicenses();
    }
  }, [user]);

  const fetchLicenses = async () => {
    setLoading(true);
    try {
      const res = await axios.get(`${API_BASE}/licenses`);
      setLicenses(res.data);
    } catch (err) {
      console.error('Failed to fetch licenses', err);
    } finally {
      setLoading(false);
    }
  };

  const handleGenerate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.subscriberId.trim()) return alert('구독자 ID를 입력해주세요.');
    setSubmitting(true);
    try {
      await axios.post(`${API_BASE}/licenses/generate`, formData);
      setFormData({ ...formData, subscriberId: '' });
      fetchLicenses();
      alert('발급 성공');
    } catch (err: any) {
      alert(err.response?.data?.error || '발급 실패');
    } finally {
      setSubmitting(false);
    }
  };

  const copyToClipboard = (text: string, id: number) => {
    navigator.clipboard.writeText(text);
    setCopySuccess(id);
    setTimeout(() => setCopySuccess(null), 2000);
  };

  const handleDelete = async (id: number) => {
    if (!confirm('정말 삭제하시겠습니까?')) return;
    try {
      await axios.delete(`${API_BASE}/licenses/${id}`);
      fetchLicenses();
    } catch (err) {
      alert('삭제 실패');
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'WAITING':
      case 'ISSUED':
        return <span className="px-2 py-0.5 rounded text-[10px] font-bold bg-amber-100 text-amber-700 whitespace-nowrap">등록 대기</span>;
      case 'ACTIVATED':
      case 'ACTIVE':
        return <span className="px-2 py-0.5 rounded text-[10px] font-bold bg-green-100 text-green-700 whitespace-nowrap">활성화됨</span>;
      default:
        return <span className="px-2 py-0.5 rounded text-[10px] font-bold bg-gray-100 text-gray-700 whitespace-nowrap">{status}</span>;
    }
  };



  if (!authChecked) return null; // Or a loader

  if (!user) {
    return <Login onLoginSuccess={(userData) => setUser(userData)} apiBase={API_BASE} />;
  }

  return (
    <div className="min-h-screen bg-[#F8FAFC] flex flex-col font-['Pretendard','sans-serif'] text-slate-800">
      <header className="bg-white border-b sticky top-0 z-20 shadow-sm">
        <div className="max-w-[1400px] w-full mx-auto px-6 py-4 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="bg-indigo-600 p-2 rounded-lg">
              <Key className="text-white w-6 h-6" />
            </div>
            <div>
              <h1 className="text-xl font-bold tracking-tight">smart_ims License Manager</h1>
              <p className="text-[11px] text-slate-400 font-medium">플랫폼 라이선스 통합 관리</p>
            </div>
          </div>
          <div className="flex items-center gap-6">
            <div className="flex items-center gap-2">
              <div className="w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center font-bold text-slate-500 text-xs">
                {user?.name?.[0] || 'A'}
              </div>
              <span className="text-sm font-bold text-slate-700">{user?.name}님</span>
            </div>
            <button onClick={handleLogout} className="flex items-center gap-2 text-slate-400 hover:text-red-500 transition-all group">
              <span className="text-xs font-bold">로그아웃</span>
              <LogOut className="w-4 h-4" />
            </button>
            <div className="w-px h-4 bg-slate-200" />
            <button onClick={fetchLicenses} className="p-2 hover:bg-slate-100 rounded-full transition-all">
              <Clock className={`w-5 h-5 text-slate-400 ${loading ? 'animate-spin' : ''}`} />
            </button>
          </div>
        </div>
      </header>

      <main className="flex-1 p-6 max-w-[1400px] w-full mx-auto grid grid-cols-12 gap-6">
        {/* Left: Registration Form */}
        <aside className="col-span-12 lg:col-span-3">
          <section className="bg-white rounded-2xl shadow-sm border border-slate-200 p-5 sticky top-24">
            <div className="flex items-center gap-2 mb-5">
              <Plus className="w-5 h-5 text-indigo-600" />
              <h2 className="text-lg font-bold">라이선스 신규 발급</h2>
            </div>
            <form onSubmit={handleGenerate} className="space-y-4">
              <div>
                <label className="block text-[11px] font-bold text-slate-400 mb-1.5 uppercase">모듈 시스템</label>
                <select className="w-full text-sm rounded-xl border-slate-200 bg-slate-50 py-2.5 px-3 focus:bg-white focus:ring-2 focus:ring-indigo-500 outline-none transition-all" value={formData.moduleCode} onChange={e => setFormData({ ...formData, moduleCode: e.target.value })}>
                  <option value="asset">스마트 자산 관리</option>
                  <option value="production">스마트 생산 관리</option>
                  <option value="monitoring">공정 모니터링 (CCTV)</option>
                </select>
              </div>
              <div>
                <label className="block text-[11px] font-bold text-slate-400 mb-1.5 uppercase">라이선스 유형</label>
                <div className="grid grid-cols-3 gap-1.5">
                  {['sub', 'demo', 'dev'].map(t => (
                    <button key={t} type="button" onClick={() => handleTypeChange(t)} className={`py-2 px-1 rounded-lg text-xs font-bold transition-all ${formData.type === t ? 'bg-indigo-600 text-white shadow-md' : 'bg-slate-100 text-slate-500 hover:bg-slate-200'}`}>
                      {t === 'dev' ? '영구' : t.toUpperCase()}
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="block text-[11px] font-bold text-slate-400 mb-1.5 uppercase">구독자 식별 ID</label>
                <input type="text" placeholder="예: SOKR-2024-01" className="w-full text-sm rounded-xl border-slate-200 bg-slate-50 py-2.5 px-3 focus:bg-white focus:ring-2 focus:ring-indigo-500 outline-none transition-all" value={formData.subscriberId} onChange={e => setFormData({ ...formData, subscriberId: e.target.value.toUpperCase() })} />
              </div>
              {formData.type !== 'dev' && (
                <div>
                  <label className="block text-[11px] font-bold text-slate-400 mb-1.5 uppercase">만기 일자</label>
                  <input
                    type="text"
                    onFocus={(e) => (e.target.type = 'date')}
                    onBlur={(e) => (e.target.type = 'text')}
                    placeholder="날짜 선택"
                    className="w-full text-sm rounded-xl border-slate-200 bg-slate-50 py-2.5 px-3 focus:bg-white focus:ring-2 focus:ring-indigo-500 outline-none transition-all"
                    value={formData.expiryDate}
                    onChange={e => setFormData({ ...formData, expiryDate: e.target.value })}
                  />
                </div>
              )}
              <button type="submit" disabled={submitting} className="w-full bg-slate-900 text-white font-bold py-3.5 rounded-xl hover:bg-indigo-600 transition-all shadow-md disabled:opacity-50">
                {submitting ? '발급 중...' : '라이선스 발급'}
              </button>
            </form>
          </section>
        </aside>

        {/* Right: Master/Detail Content Area */}
        <section className="col-span-12 lg:col-span-9 bg-white rounded-2xl shadow-sm border border-slate-200 flex flex-col min-h-[700px] overflow-hidden">
          {currentView === 'MASTER' ? (
            <>
              <div className="p-6 border-b border-slate-100 bg-slate-50/50">
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                  <div className="flex items-center gap-3">
                    <div className="bg-white p-2 rounded-lg border border-slate-200 shadow-sm">
                      <Users className="w-5 h-5 text-indigo-600" />
                    </div>
                    <div>
                      <h2 className="text-xl font-bold">라이선스 구독자 관리</h2>
                      <p className="text-[11px] text-slate-400 font-medium italic">총 {allSubscribers.length}명의 구독자가 등록되어 있습니다.</p>
                    </div>
                  </div>
                  <form onSubmit={handleSearch} className="flex gap-2">
                    <div className="relative">
                      <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                      <input type="text" placeholder="구독자 ID 검색..." className="pl-9 pr-3 py-2 text-sm rounded-xl border-slate-200 bg-white focus:ring-2 focus:ring-indigo-500 outline-none w-64 shadow-sm" value={searchQuery} onChange={e => setSearchQuery(e.target.value)} />
                    </div>
                    <button type="submit" className="bg-white border border-slate-200 px-4 py-2 rounded-xl text-sm font-bold text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition-all shadow-sm">조회</button>
                  </form>
                </div>
              </div>
              <div className="flex-1 overflow-auto">
                <table className="w-full text-left border-collapse">
                  <thead className="bg-[#FBFCFD] sticky top-0 z-10 border-b border-slate-100">
                    <tr>
                      <th className="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest w-24 text-center">No.</th>
                      <th className="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">구독자 ID</th>
                      <th className="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest text-right">관리</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-50">
                    {filteredSubscribers.length > 0 ? (
                      filteredSubscribers.map((sub: string, idx: number) => (
                        <tr key={sub} className="hover:bg-[#F8FAFF] group transition-colors">
                          <td className="px-8 py-5 text-xs font-mono text-slate-400 text-center">{idx + 1}</td>
                          <td className="px-8 py-5 text-sm font-bold text-slate-800">{sub}</td>
                          <td className="px-8 py-5 text-right">
                            <button onClick={() => handleManage(sub)} className="inline-flex items-center gap-1 px-4 py-1.5 bg-slate-100 text-slate-600 text-xs font-bold rounded-lg hover:bg-indigo-600 hover:text-white transition-all">
                              관리 <ChevronRight className="w-3 h-3" />
                            </button>
                          </td>
                        </tr>
                      ))
                    ) : (
                      <tr>
                        <td colSpan={3} className="p-32 text-center text-slate-300">
                          <Search className="w-12 h-12 mx-auto mb-4 opacity-10" />
                          <p className="text-lg font-bold">검색 결과가 없습니다.</p>
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </>
          ) : (
            <>
              <div className="p-6 border-b border-slate-100 bg-[#FBFCFD]">
                <div className="flex items-center gap-4">
                  <button onClick={handleBack} className="p-2 hover:bg-white rounded-xl border border-transparent hover:border-slate-200 shadow-sm transition-all group">
                    <ArrowLeft className="w-5 h-5 text-slate-400 group-hover:text-indigo-600" />
                  </button>
                  <div>
                    <h2 className="text-xl font-bold flex items-center gap-2">
                      <span className="text-indigo-600">{selectedSubscriber}</span> 발급 이력
                    </h2>
                    <p className="text-[11px] text-slate-400 font-medium">총 {detailLicenses.length}건의 이력이 확인되었습니다.</p>
                  </div>
                </div>
              </div>
              <div className="flex-1 overflow-auto">
                <table className="w-full text-left border-collapse">
                  <thead className="bg-[#FBFCFD] sticky top-0 z-10 border-b border-slate-100">
                    <tr>
                      <th className="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest w-20 text-center">No.</th>
                      <th className="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest w-28">상태</th>
                      <th className="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">라이선스 상세 키</th>
                      <th className="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest w-36">모듈</th>
                      <th className="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest w-24 text-center">유형</th>
                      <th className="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest w-16">삭제</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-50">
                    {detailLicenses.map((lic: License, idx: number) => (
                      <tr key={lic.id} className="hover:bg-[#F8FAFF] transition-colors">
                        <td className="px-8 py-6 text-xs font-mono text-slate-400 text-center">{idx + 1}</td>
                        <td className="px-8 py-6">{getStatusBadge(lic.status)}</td>
                        <td className="px-8 py-6">
                          <div className="relative group">
                            <div className="text-[10px] font-mono bg-slate-900 text-indigo-300 p-3 rounded-lg break-all shadow-inner">
                              {lic.license_key}
                            </div>
                            <button onClick={() => copyToClipboard(lic.license_key, lic.id)} className={`absolute right-2 top-2 p-1.5 rounded-md transition-all ${copySuccess === lic.id ? 'bg-green-500 text-white' : 'bg-slate-800 text-slate-500 hover:text-white'}`}>
                              {copySuccess === lic.id ? <CheckCircle className="w-3 h-3" /> : <Copy className="w-3 h-3" />}
                            </button>
                          </div>
                        </td>
                        <td className="px-8 py-6 text-sm font-bold text-slate-800">{lic.module_code.toUpperCase()}</td>
                        <td className="px-8 py-6 text-center text-[10px] font-black uppercase text-slate-400">{lic.license_type}</td>
                        <td className="px-8 py-6 text-center">
                          <button onClick={() => handleDelete(lic.id)} className="p-2 text-slate-300 hover:text-red-500 hover:bg-red-50 rounded-lg transition-all">
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </>
          )}
        </section>
      </main>

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 5px; height: 5px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #E2E8F0; border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: #CBD5E1; }
      `}</style>
    </div>
  );
}

export default App;
