import { useState, useEffect } from 'react';
import {
  Plus,
  FolderOpen,
  Download,
  Search,
  X,
  ChevronLeft,
  ChevronRight,
  CheckCircle,
  XCircle,
} from 'lucide-react';
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="p-6 space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-white">라이선스 관리</h1>
        <div className="flex items-center space-x-2">
          <button
            onClick={handleAdd}
            disabled={loading}
            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"
          >
            <Plus className="w-4 h-4" />
            <span>추가</span>
          </button>
          <button
            onClick={handleExportCSV}
            disabled={loading}
            className="flex items-center space-x-2 px-4 py-2 bg-green-500 hover:bg-green-600 disabled:bg-gray-600 text-white rounded-lg transition-colors"
          >
            <Download className="w-4 h-4" />
            <span>CSV</span>
          </button>
        </div>
      </div>

      {/* Search */}
      <div className="flex items-center space-x-2">
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/50" />
          <input
            type="text"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            placeholder="검색 (제품명, 버전, 공급업체, 제조사, S/N, 자재번호, 비고)"
            className="w-full pl-10 pr-10 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:border-blue-500"
          />
          {searchText && (
            <button
              onClick={() => setSearchText('')}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-white/50 hover:text-white"
            >
              <X className="w-4 h-4" />
            </button>
          )}
        </div>
      </div>

      {/* Table */}
      <div className="glass-effect rounded-lg overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full border-collapse">
            <thead className="bg-white/10">
              <tr>
                <th className="px-4 py-3 text-center text-sm font-semibold text-white border-r border-white/10 w-16">상태</th>
                <th className="px-4 py-3 text-left text-sm font-semibold text-white border-r border-white/10" style={{ width: '25%' }}>제품명</th>
                <th className="px-4 py-3 text-left text-sm font-semibold text-white border-r border-white/10" style={{ width: '25%' }}>버전</th>
                <th className="px-4 py-3 text-left text-sm font-semibold text-white border-r border-white/10 w-20">수량</th>
                <th className="px-4 py-3 text-left text-sm font-semibold text-white border-r border-white/10" style={{ width: '12%' }}>사용자</th>
                <th className="px-4 py-3 text-left text-sm font-semibold text-white" style={{ width: '15%' }}>S/N</th>
              </tr>
            </thead>
            <tbody>
              {loading && (
                <tr>
                  <td colSpan={6} className="px-4 py-8 text-center text-white/70">
                    로딩 중...
                  </td>
                </tr>
              )}
              {!loading && paginatedList.length === 0 && (
                <tr>
                  <td colSpan={6} className="px-4 py-8 text-center text-white/70">
                    데이터가 없습니다.
                  </td>
                </tr>
              )}
              {!loading &&
                paginatedList.map((item) => (
                  <tr
                    key={item.idx}
                    onClick={() => handleRowClick(item)}
                    className={`border-t border-white/10 hover:bg-white/10 cursor-pointer transition-colors ${
                      item.expire ? 'bg-red-500/10' : ''
                    }`}
                  >
                    <td className="px-4 py-3 text-center border-r border-white/10">
                      <div className="flex justify-center" title={item.expire ? '만료' : '유효'}>
                        {item.expire ? (
                          <XCircle className="w-5 h-5 text-red-500" />
                        ) : (
                          <CheckCircle className="w-5 h-5 text-green-500" />
                        )}
                      </div>
                    </td>
                    <td className="px-4 py-3 text-sm text-white border-r border-white/10 max-w-xs">
                      <div className="flex items-center space-x-2">
                        <button
                          onClick={(e) => handleOpenFolder(item, e)}
                          className="p-1 text-yellow-400 hover:text-yellow-300 transition-colors flex-shrink-0"
                          title="폴더 열기"
                        >
                          <FolderOpen className="w-4 h-4" />
                        </button>
                        <span className="break-words">{item.name}</span>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-sm text-white border-r border-white/10 break-words">{item.version}</td>
                    <td className="px-4 py-3 text-sm text-white border-r border-white/10">{item.qty}</td>
                    <td className="px-4 py-3 text-sm text-white border-r border-white/10 break-words max-w-[8rem]">{item.uids}</td>
                    <td className="px-4 py-3 text-sm text-white break-words">{item.serialNo}</td>
                  </tr>
                ))}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between px-4 py-3 border-t border-white/10">
            <div className="text-sm text-white/70">
              전체 {filteredList.length}건 중 {(currentPage - 1) * pageSize + 1}~
              {Math.min(currentPage * pageSize, filteredList.length)}건
            </div>
            <div className="flex items-center space-x-2">
              <button
                onClick={goToPreviousPage}
                disabled={currentPage === 1}
                className="p-2 text-white/70 hover:text-white disabled:text-white/30 disabled:cursor-not-allowed"
              >
                <ChevronLeft className="w-5 h-5" />
              </button>
              <span className="text-sm text-white">
                {currentPage} / {totalPages}
              </span>
              <button
                onClick={goToNextPage}
                disabled={currentPage === totalPages}
                className="p-2 text-white/70 hover:text-white disabled:text-white/30 disabled:cursor-not-allowed"
              >
                <ChevronRight className="w-5 h-5" />
              </button>
            </div>
          </div>
        )}
      </div>

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