import { useState, useEffect } from 'react';
import { Building, Search, RefreshCw } from 'lucide-react';
import { comms } from '@/communication';
import type { CustomItem } from '@/types';

export function Customs() {
  const [customsList, setCustomsList] = useState<CustomItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchKey, setSearchKey] = useState('');

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

  const loadData = async () => {
    setLoading(true);
    try {
      const response = await comms.getCustomsList(searchKey);
      if (response.Success && response.Data) {
        setCustomsList(response.Data);
      } else {
        console.error('업체정보 조회 실패:', response.Message);
        alert(response.Message || '업체정보 조회에 실패했습니다.');
        setCustomsList([]);
      }
    } catch (error) {
      console.error('업체정보 로드 오류:', error);
      alert('데이터를 불러오는 중 오류가 발생했습니다.');
      setCustomsList([]);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    loadData();
  };

  return (
    <div className="space-y-6 animate-fade-in">
      {/* 검색 필터 */}
      <div className="glass-effect rounded-2xl p-6">
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2 flex-1">
            <label className="text-white/70 text-sm font-medium whitespace-nowrap">검색어</label>
            <input
              type="text"
              value={searchKey}
              onChange={(e) => setSearchKey(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
              placeholder="업체명, 대표자, 전화번호, 이메일, 담당자 등"
              className="flex-1 h-10 bg-white/20 border border-white/30 rounded-lg px-3 text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400"
            />
          </div>

          <button
            onClick={handleSearch}
            disabled={loading}
            className="h-10 bg-primary-500 hover:bg-primary-600 text-white px-6 rounded-lg transition-colors flex items-center justify-center disabled:opacity-50"
          >
            {loading ? (
              <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
            ) : (
              <Search className="w-4 h-4 mr-2" />
            )}
            조회
          </button>
        </div>
      </div>

      {/* 업체 목록 */}
      <div className="glass-effect rounded-2xl overflow-hidden">
        <div className="px-6 py-4 border-b border-white/10 flex items-center justify-between">
          <h3 className="text-lg font-semibold text-white flex items-center">
            <Building className="w-5 h-5 mr-2" />
            업체 정보
          </h3>
          <span className="text-white/60 text-sm">{customsList.length}건</span>
        </div>

        <div className="divide-y divide-white/10 max-h-[calc(100vh-300px)] overflow-y-auto">
          {loading ? (
            <div className="px-6 py-8 text-center">
              <div className="flex items-center justify-center">
                <RefreshCw className="w-5 h-5 mr-2 animate-spin text-white/50" />
                <span className="text-white/50">데이터를 불러오는 중...</span>
              </div>
            </div>
          ) : customsList.length === 0 ? (
            <div className="px-6 py-8 text-center">
              <Building className="w-12 h-12 mx-auto mb-3 text-white/30" />
              <p className="text-white/50">조회된 데이터가 없습니다.</p>
              <p className="text-white/40 text-sm mt-2">업체정보 API 구현이 필요합니다.</p>
            </div>
          ) : (
            customsList.map((item) => (
              <div
                key={item.idx}
                className="px-6 py-4 hover:bg-white/5 transition-colors"
              >
                <div className="flex items-center justify-between gap-4">
                  <div className="flex-1 min-w-0">
                    <h4 className="text-white font-medium mb-1">
                      {item.name}
                      {item.name2 && <span className="text-white/60 text-sm ml-2">({item.name2})</span>}
                    </h4>
                    <div className="flex items-center gap-4 text-white/60 text-sm flex-wrap">
                      {item.grp && <div>구분: {item.grp}</div>}
                      {item.owner && <div>대표: {item.owner}</div>}
                      {item.uptae && <div>업태: {item.uptae}</div>}
                      {item.address && <div>{item.address}</div>}
                    </div>
                  </div>
                  <div className="flex flex-col items-end gap-1 flex-shrink-0 text-white/60 text-sm">
                    {item.tel && <div>{item.tel}</div>}
                    {item.email && <div>{item.email}</div>}
                    {item.staff && <div>담당: {item.staff}</div>}
                  </div>
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}
