import { useState, useEffect } from 'react';
import {
  Plus,
  FolderOpen,
  Download,
  Search,
  ChevronLeft,
  ChevronRight,
  CheckCircle,
  XCircle,
  ShieldCheck,
  RefreshCw,
} from 'lucide-react';
import { clsx } from 'clsx';
import { comms } from '@/communication';
import { LicenseEditDialog } from './LicenseEditDialog';
import type { LicenseItem } from '@/types';

export function LicenseList() {
  const [list, setList] = useState<LicenseItem[]>([]);
  const [filteredList, setFilteredList] = useState<LicenseItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedItem, setSelectedItem] = useState<LicenseItem | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);

  // Pagination
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 25;

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

  useEffect(() => {
    applyFilter();
  }, [searchText, list]);

  const loadData = async () => {
    setLoading(true);
    try {
      const response = await comms.getLicenseList();
      if (response.Success && response.Data) {
        setList(response.Data);
      } else {
        alert(response.Message || '라이선스 목록을 불러오는데 실패했습니다.');
      }
    } catch (error) {
      console.error('Failed to load license list:', error);
      alert('라이선스 목록을 불러오는데 실패했습니다.');
    } finally {
      setLoading(false);
    }
  };

  const applyFilter = () => {
    if (!searchText.trim()) {
      setFilteredList(list);
      return;
    }

    const search = searchText.toLowerCase();
    const filtered = list.filter((item) => {
      return (
        item.name?.toLowerCase().includes(search) ||
        item.version?.toLowerCase().includes(search) ||
        item.supply?.toLowerCase().includes(search) ||
        item.manu?.toLowerCase().includes(search) ||
        item.serialNo?.toLowerCase().includes(search) ||
        item.meterialNo?.toLowerCase().includes(search) ||
        item.remark?.toLowerCase().includes(search)
      );
    });
    setFilteredList(filtered);
    setCurrentPage(1);
  };

  const handleAdd = () => {
    setSelectedItem({
      expire: false,
      name: '',
      version: '',
      meterialNo: '',
      supply: '',
      qty: 1,
      uids: '',
      serialNo: '',
      remark: '',
      sdate: new Date().toISOString().split('T')[0],
      edate: '',
      manu: '',
    });
    setIsDialogOpen(true);
  };

  const handleRowClick = (item: LicenseItem) => {
    setSelectedItem(item);
    setIsDialogOpen(true);
  };

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

    try {
      setLoading(true);
      let response;

      if (formData.idx) {
        // Update
        response = await comms.updateLicense(
          formData.idx,
          formData.name!,
          formData.version || '',
          formData.meterialNo || '',
          formData.supply || '',
          formData.qty || 1,
          formData.uids || '',
          formData.serialNo || '',
          formData.remark || '',
          formData.sdate || '',
          formData.edate || '',
          formData.manu || '',
          formData.expire || false
        );
      } else {
        // Add
        response = await comms.addLicense(
          formData.name!,
          formData.version || '',
          formData.meterialNo || '',
          formData.supply || '',
          formData.qty || 1,
          formData.uids || '',
          formData.serialNo || '',
          formData.remark || '',
          formData.sdate || '',
          formData.edate || '',
          formData.manu || '',
          formData.expire || false
        );
      }

      if (response.Success) {
        alert(response.Message || '저장되었습니다.');
        await loadData();
      } else {
        alert(response.Message || '저장에 실패했습니다.');
      }
    } catch (error) {
      console.error('Failed to save license:', error);
      alert('저장에 실패했습니다.');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (idx: number) => {
    try {
      setLoading(true);
      const response = await comms.deleteLicense(idx);
      if (response.Success) {
        alert(response.Message || '삭제되었습니다.');
        await loadData();
      } else {
        alert(response.Message || '삭제에 실패했습니다.');
      }
    } catch (error) {
      console.error('Failed to delete license:', error);
      alert('삭제에 실패했습니다.');
    } finally {
      setLoading(false);
    }
  };

  const handleOpenFolder = async (item: LicenseItem, e: React.MouseEvent) => {
    e.stopPropagation();
    if (!item.idx) {
      alert('저장된 자료만 폴더를 열 수 있습니다.');
      return;
    }

    try {
      const response = await comms.openLicenseFolder(item.idx);
      if (!response.Success) {
        alert(response.Message || '폴더 열기에 실패했습니다.');
      }
    } catch (error) {
      console.error('Failed to open folder:', error);
      alert('폴더 열기에 실패했습니다.');
    }
  };

  const handleExportCSV = async () => {
    const filename = `license_${new Date().toISOString().split('T')[0]}.csv`;
    const filepath = `C:\\Temp\\${filename}`;

    try {
      const response = await comms.exportLicenseCSV(filepath);
      if (response.Success) {
        alert(`CSV 파일이 생성되었습니다.\n\n${filepath}`);
      } else {
        alert(response.Message || 'CSV 내보내기에 실패했습니다.');
      }
    } catch (error) {
      console.error('Failed to export CSV:', error);
      alert('CSV 내보내기에 실패했습니다.');
    }
  };

  const handleCloseDialog = () => {
    setIsDialogOpen(false);
    setSelectedItem(null);
  };

  // Pagination
  const totalPages = Math.ceil(filteredList.length / pageSize);
  const paginatedList = filteredList.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize
  );

  const goToPreviousPage = () => {
    setCurrentPage((prev) => Math.max(1, prev - 1));
  };

  const goToNextPage = () => {
    setCurrentPage((prev) => Math.min(totalPages, prev + 1));
  };

  return (
    <div className="flex flex-col h-full animate-fade-in bg-white/[0.02]">
      {/* 리스트 헤더 */}
      <div className="bg-white/5 border-b border-white/10 px-6 py-4 flex items-center justify-between backdrop-blur-md sticky top-0 z-20">
        <div className="flex items-center gap-4">
          <div className="p-2 bg-primary-500/20 rounded-lg">
            <ShieldCheck className="w-6 h-6 text-primary-400" />
          </div>
          <div>
            <h2 className="text-lg font-bold text-white leading-tight">라이선스 관리</h2>
            <p className="text-[10px] text-white/40 uppercase tracking-wider font-medium">License Management</p>
          </div>
        </div>

        <div className="flex items-center gap-3">
          {/* 검색 바 */}
          <div className="relative group w-80">
            <Search className="absolute left-3 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={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              placeholder="검색어 입력..."
              className="w-full bg-white/5 border border-white/10 rounded-xl pl-9 pr-8 py-1.5 text-xs text-white placeholder-white/20 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all backdrop-blur-sm"
            />
            {searchText && (
              <button
                onClick={() => setSearchText('')}
                className="absolute right-2.5 top-1/2 -translate-y-1/2 text-white/20 hover:text-white transition-colors"
              >
                <XCircle className="w-3.5 h-3.5" />
              </button>
            )}
          </div>

          {/* 건수 */}
          <div className="flex items-center gap-2 bg-white/5 px-3 py-1.5 rounded-xl border border-white/10 h-[38px]">
            <span className="text-primary-400 font-bold text-sm">{filteredList.length}</span>
            <span className="text-white/40 text-[10px] uppercase">건</span>
          </div>

          {/* 새로고침 */}
          <button
            onClick={loadData}
            disabled={loading}
            className="p-2 bg-white/5 hover:bg-white/10 border border-white/10 rounded-xl text-white/70 hover:text-white transition-all disabled:opacity-50"
            title="새로고침"
          >
            <RefreshCw className={clsx("w-4 h-4", loading && "animate-spin")} />
          </button>

          {/* CSV */}
          <button
            onClick={handleExportCSV}
            disabled={loading}
            className="p-2 bg-white/5 hover:bg-green-500/20 border border-white/10 rounded-xl text-white/70 hover:text-green-400 transition-all disabled:opacity-50"
            title="CSV 내보내기"
          >
            <Download className="w-4 h-4" />
          </button>

          {/* 추가 */}
          <button
            onClick={handleAdd}
            className="p-2 bg-primary-500 hover:bg-primary-600 border border-white/20 rounded-xl text-white transition-all shadow-lg shadow-primary-500/20 active:scale-95"
            title="추가"
          >
            <Plus className="w-4 h-4" />
          </button>
        </div>
      </div>

      <div className="flex-1 overflow-hidden flex flex-col p-6">
        {/* 테이블 메인 섹션 */}
        <div className="flex-1 glass-effect rounded-2xl border border-white/10 flex flex-col overflow-hidden shadow-2xl">
          {/* 컬럼 헤더 */}
          <div className="bg-white/10 px-6 py-3 border-b border-white/5 flex items-center gap-4 sticky top-0 z-10">
            <div className="w-12 text-center text-xs font-medium text-white/70 uppercase">상태</div>
            <div className="flex-1 flex items-center gap-4">
              <div className="w-1/4 text-xs font-medium text-white/70 uppercase">제품명</div>
              <div className="w-1/4 text-xs font-medium text-white/70 uppercase">버전</div>
              <div className="w-20 text-xs font-medium text-white/70 uppercase text-center">수량</div>
              <div className="w-32 text-xs font-medium text-white/70 uppercase">사용자</div>
              <div className="flex-1 text-xs font-medium text-white/70 uppercase">S/N</div>
            </div>
          </div>

          <div className="divide-y divide-white/5 overflow-y-auto custom-scrollbar flex-1">
            {loading ? (
              <div className="px-6 py-12 text-center">
                <RefreshCw className="w-10 h-10 mx-auto mb-4 animate-spin text-primary-500/50" />
                <p className="text-white/50 font-medium text-sm">데이터를 불러오는 중...</p>
              </div>
            ) : paginatedList.length === 0 ? (
              <div className="px-6 py-20 text-center">
                <div className="relative inline-block mb-4">
                  <ShieldCheck className="w-16 h-16 mx-auto text-white/10" />
                </div>
                <p className="text-white/30 font-medium">조회된 라이선스가 없습니다.</p>
              </div>
            ) : (
              paginatedList.map((item) => (
                <div
                  key={item.idx}
                  onClick={() => handleRowClick(item)}
                  className={clsx(
                    "px-6 py-3 hover:bg-white/[0.03] transition-all cursor-pointer group flex items-center gap-4 border-b border-white/[0.02]",
                    item.expire && "bg-danger-500/[0.03]"
                  )}
                >
                  <div className="w-12 flex justify-center shrink-0">
                    <div className={clsx(
                      "w-8 h-8 rounded-lg flex items-center justify-center transition-all group-hover:scale-110",
                      item.expire ? "bg-danger-500/20 text-danger-400" : "bg-success-500/20 text-success-400"
                    )}>
                      {item.expire ? (
                        <XCircle className="w-4 h-4" />
                      ) : (
                        <CheckCircle className="w-4 h-4" />
                      )}
                    </div>
                  </div>

                  <div className="flex-1 flex items-center gap-4 min-w-0">
                    <div className="w-1/4 min-w-0 flex items-center gap-2">
                      <button
                        onClick={(e) => handleOpenFolder(item, e)}
                        className="p-1 text-warning-400 hover:text-warning-300 transition-colors shrink-0"
                        title="폴더 열기"
                      >
                        <FolderOpen className="w-4 h-4" />
                      </button>
                      <span className="text-sm font-bold text-white group-hover:text-primary-400 transition-colors truncate">
                        {item.name}
                      </span>
                    </div>
                    <div className="w-1/4 min-w-0">
                      <span className="text-sm text-white/60 truncate" title={item.version}>{item.version || '-'}</span>
                    </div>
                    <div className="w-20 shrink-0 text-center">
                      <span className="text-sm font-medium text-white/70">{item.qty || 0}</span>
                    </div>
                    <div className="w-32 shrink-0">
                      <span className="text-sm text-white/50 truncate" title={item.uids}>{item.uids || '-'}</span>
                    </div>
                    <div className="flex-1 min-w-0">
                      <span className="text-xs font-mono text-white/40 truncate" title={item.serialNo}>{item.serialNo || '-'}</span>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="bg-white/5 px-6 py-3 border-t border-white/10 flex items-center justify-between backdrop-blur-md">
              <div className="flex items-center gap-2">
                <span className="text-white/30 text-[10px] uppercase font-bold tracking-wider">Page</span>
                <span className="text-white text-sm font-mono font-bold">{currentPage}</span>
                <span className="text-white/20 text-xs italic">of</span>
                <span className="text-white/60 text-sm font-mono">{totalPages}</span>
              </div>

              <div className="flex items-center gap-1">
                <button
                  onClick={goToPreviousPage}
                  disabled={currentPage === 1}
                  className="p-1.5 rounded-lg hover:bg-white/10 text-white/70 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-all"
                >
                  <ChevronLeft className="w-5 h-5" />
                </button>

                <div className="flex items-center gap-1 mx-2">
                  {totalPages <= 5 ? (
                    [...Array(totalPages)].map((_, i) => (
                      <button
                        key={i + 1}
                        onClick={() => setCurrentPage(i + 1)}
                        className={clsx(
                          "w-8 h-8 rounded-lg text-xs font-bold transition-all",
                          currentPage === i + 1
                            ? "bg-primary-500 text-white shadow-lg shadow-primary-500/30"
                            : "text-white/40 hover:bg-white/10 hover:text-white"
                        )}
                      >
                        {i + 1}
                      </button>
                    ))
                  ) : (
                    <span className="text-white/40 text-xs px-2">{currentPage} / {totalPages}</span>
                  )}
                </div>

                <button
                  onClick={goToNextPage}
                  disabled={currentPage === totalPages}
                  className="p-1.5 rounded-lg hover:bg-white/10 text-white/70 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-all"
                >
                  <ChevronRight className="w-5 h-5" />
                </button>
              </div>

              <div className="flex items-center gap-2">
                <span className="text-white/30 text-[10px] uppercase font-bold tracking-wider">Total</span>
                <span className="text-primary-400 text-sm font-mono font-bold leading-none">{filteredList.length}</span>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Edit Dialog */}
      <LicenseEditDialog
        item={selectedItem}
        isOpen={isDialogOpen}
        onClose={handleCloseDialog}
        onSave={handleSave}
        onDelete={handleDelete}
      />
    </div>
  );
}
