import { useState, useEffect } from 'react';
import { Search, Plus, Package, Image, Users, TrendingDown, ShoppingCart } from 'lucide-react';
import { clsx } from 'clsx';
import { comms } from '@/communication';
import { ItemInfo, ItemDetail, SupplierStaff, PurchaseHistoryItem } from '@/types';
import { ItemEditDialog } from '@/components/items';

export function ItemsPage() {
  const [categories, setCategories] = useState<string[]>([]);
  const [items, setItems] = useState<ItemInfo[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [searchKey, setSearchKey] = useState('');
  const [loading, setLoading] = useState(false);
  const [filter, setFilter] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState<ItemInfo | null>(null);

  // 우측 패널 상태
  const [selectedItemDetail, setSelectedItemDetail] = useState<ItemDetail | null>(null);
  const [itemImage, setItemImage] = useState<string | null>(null);
  const [supplierStaff, setSupplierStaff] = useState<SupplierStaff[]>([]);
  const [incomingHistory, setIncomingHistory] = useState<PurchaseHistoryItem[]>([]);
  const [orderHistory, setOrderHistory] = useState<PurchaseHistoryItem[]>([]);
  const [detailLoading, setDetailLoading] = useState(false);

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

  const loadCategories = async () => {
    try {
      const result = await comms.getItemCategories();
      if (result.Success && result.Data) {
        setCategories(result.Data);
      }
    } catch (error) {
      console.error('카테고리 로드 실패:', error);
    }
  };

  const loadItems = async () => {
    if (!searchKey.trim()) {
      alert('검색어를 입력하세요');
      return;
    }
    setLoading(true);
    // 선택 초기화
    setSelectedItemDetail(null);
    setItemImage(null);
    setSupplierStaff([]);
    setIncomingHistory([]);
    setOrderHistory([]);
    try {
      const result = await comms.getItemList(selectedCategory, searchKey);
      setItems(result);
    } catch (error) {
      console.error('품목 로드 실패:', error);
    } finally {
      setLoading(false);
    }
  };

  // 품목 선택 시 상세 정보 로드
  const loadItemDetail = async (item: ItemInfo) => {
    setDetailLoading(true);
    try {
      // 병렬로 상세정보, 이미지, 구매내역 로드
      const [detailRes, imageRes, incomingRes, orderRes] = await Promise.all([
        comms.getItemDetail(item.idx),
        comms.getItemImage(item.idx),
        comms.getIncomingHistory(item.idx),
        comms.getOrderHistory(item.idx)
      ]);

      if (detailRes.Success && detailRes.Data) {
        setSelectedItemDetail(detailRes.Data);

        // 공급처 담당자 로드 (supplyidx가 있을 때만)
        if (detailRes.Data.supplyidx && detailRes.Data.supplyidx > 0) {
          const staffRes = await comms.getSupplierStaff(detailRes.Data.supplyidx);
          if (staffRes.Success && staffRes.Data) {
            setSupplierStaff(staffRes.Data);
          } else {
            setSupplierStaff([]);
          }
        } else {
          setSupplierStaff([]);
        }
      }

      if (imageRes.Success && imageRes.Data) {
        setItemImage(imageRes.Data);
      } else {
        setItemImage(null);
      }

      if (incomingRes.Success && incomingRes.Data) {
        setIncomingHistory(incomingRes.Data);
      } else {
        setIncomingHistory([]);
      }

      if (orderRes.Success && orderRes.Data) {
        setOrderHistory(orderRes.Data);
      } else {
        setOrderHistory([]);
      }
    } catch (error) {
      console.error('상세 정보 로드 실패:', error);
    } finally {
      setDetailLoading(false);
    }
  };

  const handleSave = async (item: ItemInfo) => {
    const response = await comms.saveItem(item);
    if (response.Success) {
      setDialogOpen(false);
      setSelectedItem(null);
      if (searchKey) loadItems();
    } else {
      alert(response.Message || '저장 실패');
    }
  };

  const handleDelete = async (idx: number) => {
    const response = await comms.deleteItem(idx);
    if (response.Success) {
      setDialogOpen(false);
      setSelectedItem(null);
      setItems(items.filter((i) => i.idx !== idx));
      // 상세 패널 초기화
      if (selectedItemDetail?.idx === idx) {
        setSelectedItemDetail(null);
        setItemImage(null);
        setSupplierStaff([]);
        setIncomingHistory([]);
        setOrderHistory([]);
      }
    } else {
      alert(response.Message || '삭제 실패');
    }
  };

  const handleAddNew = () => {
    const newItem: ItemInfo = {
      idx: 0,
      sid: '',
      cate: selectedCategory !== 'all' ? selectedCategory : '',
      name: '',
      model: '',
      scale: '',
      unit: '',
      price: 0,
      supply: '',
      manu: '',
      storage: '',
      disable: false,
      memo: '',
    };
    setSelectedItem(newItem);
    setDialogOpen(true);
  };

  const handleRowClick = (item: ItemInfo) => {
    // 상세 정보 로드
    loadItemDetail(item);
  };

  const handleRowDoubleClick = (item: ItemInfo) => {
    setSelectedItem(item);
    setDialogOpen(true);
  };

  const filteredItems = items.filter(
    (i) =>
      (i.sid ?? '').toLowerCase().includes(filter.toLowerCase()) ||
      (i.name ?? '').toLowerCase().includes(filter.toLowerCase()) ||
      (i.model ?? '').toLowerCase().includes(filter.toLowerCase())
  );

  return (
    <div className="h-full flex flex-col">
      {/* 헤더 */}
      <div className="glass-effect rounded-xl p-4 mb-4">
        <div className="flex items-center gap-4 flex-wrap">
          <select
            value={selectedCategory}
            onChange={(e) => setSelectedCategory(e.target.value)}
            className="px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white min-w-[150px]"
          >
            <option value="all" className="bg-slate-800">-- 전체 --</option>
            {categories.map((c) => (
              <option key={c} value={c} className="bg-slate-800">{c}</option>
            ))}
          </select>

          <div className="flex-1 flex items-center gap-2">
            <div className="relative flex-1 max-w-xs">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/40" />
              <input
                type="text"
                value={searchKey}
                onChange={(e) => setSearchKey(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && loadItems()}
                placeholder="품목명/SID/모델 검색..."
                className="w-full pl-9 pr-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40"
              />
            </div>
            <button
              onClick={loadItems}
              className="flex items-center gap-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg text-white transition-colors"
            >
              <Search className="w-4 h-4" />
              검색
            </button>
          </div>

          <div className="flex items-center gap-2">
            <input
              type="text"
              value={filter}
              onChange={(e) => setFilter(e.target.value)}
              placeholder="필터..."
              className="px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 w-32"
            />
            <button
              onClick={handleAddNew}
              className="flex items-center gap-1 px-3 py-2 bg-green-600 hover:bg-green-700 rounded-lg text-white transition-colors"
            >
              <Plus className="w-4 h-4" />
              추가
            </button>
          </div>
        </div>
      </div>

      {/* 메인 컨텐츠: 목록 + 상세 패널 */}
      <div className="flex-1 flex gap-4 min-h-0">
        {/* 품목 목록 (좌측) */}
        <div className="flex-1 glass-effect rounded-xl overflow-hidden flex flex-col">
          <div className="p-4 border-b border-white/10 flex items-center gap-2">
            <Package className="w-5 h-5 text-white/70" />
            <h2 className="text-lg font-semibold text-white">품목 목록</h2>
            <span className="text-sm text-white/50">({filteredItems.length}건)</span>
          </div>

          <div className="flex-1 overflow-auto">
            {loading ? (
              <div className="flex items-center justify-center h-32">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-white"></div>
              </div>
            ) : (
              <table className="w-full text-sm">
                <thead className="bg-white/5 sticky top-0">
                  <tr>
                    <th className="px-3 py-2 text-left font-medium text-white/70 w-28">SID</th>
                    <th className="px-3 py-2 text-left font-medium text-white/70 w-20">분류</th>
                    <th className="px-3 py-2 text-left font-medium text-white/70">품명</th>
                    <th className="px-3 py-2 text-left font-medium text-white/70">모델</th>
                    <th className="px-3 py-2 text-right font-medium text-white/70 w-24">단가</th>
                    <th className="px-3 py-2 text-left font-medium text-white/70 w-24">공급처</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/5">
                  {filteredItems.map((item) => (
                    <tr
                      key={item.idx || 'new'}
                      onClick={() => handleRowClick(item)}
                      onDoubleClick={() => handleRowDoubleClick(item)}
                      className={clsx(
                        'hover:bg-white/10 transition-colors cursor-pointer',
                        item.disable && 'opacity-50',
                        selectedItemDetail?.idx === item.idx && 'bg-blue-600/30'
                      )}
                    >
                      <td className="px-3 py-2 text-white font-mono">{item.sid}</td>
                      <td className="px-3 py-2 text-white/70">{item.cate}</td>
                      <td className="px-3 py-2 text-white">{item.name}</td>
                      <td className="px-3 py-2 text-white/70">{item.model}</td>
                      <td className="px-3 py-2 text-white text-right">{(item.price ?? 0).toLocaleString()}</td>
                      <td className="px-3 py-2 text-white/70">{item.supply}</td>
                    </tr>
                  ))}
                  {filteredItems.length === 0 && (
                    <tr>
                      <td colSpan={6} className="px-4 py-8 text-center text-white/50">
                        {items.length === 0 ? '검색어를 입력하고 검색 버튼을 클릭하세요.' : '검색 결과가 없습니다.'}
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            )}
          </div>
        </div>

        {/* 상세 패널 (우측) */}
        <div className="w-80 flex flex-col gap-4">
          {/* 이미지 */}
          <div className="glass-effect rounded-xl p-3">
            <div className="flex items-center gap-2 mb-2 border-b border-white/10 pb-2">
              <Image className="w-4 h-4 text-white/70" />
              <h3 className="text-sm font-medium text-white">품목 이미지</h3>
            </div>
            <div className="aspect-[4/3] bg-white/5 rounded-lg flex items-center justify-center overflow-hidden">
              {detailLoading ? (
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-white/50"></div>
              ) : itemImage ? (
                <img
                  src={`data:image/jpeg;base64,${itemImage}`}
                  alt="품목 이미지"
                  className="max-w-full max-h-full object-contain"
                />
              ) : (
                <span className="text-white/30 text-sm">이미지 없음</span>
              )}
            </div>
          </div>

          {/* 공급처 담당자 */}
          <div className="glass-effect rounded-xl p-3">
            <div className="flex items-center gap-2 mb-2 border-b border-white/10 pb-2">
              <Users className="w-4 h-4 text-white/70" />
              <h3 className="text-sm font-medium text-white">
                {selectedItemDetail?.supply ? `[${selectedItemDetail.supply}] 담당자` : '공급처 담당자'}
              </h3>
            </div>
            <div className="max-h-32 overflow-auto">
              {detailLoading ? (
                <div className="text-center py-2">
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white/50 mx-auto"></div>
                </div>
              ) : supplierStaff.length > 0 ? (
                <table className="w-full text-xs">
                  <thead className="bg-white/5">
                    <tr>
                      <th className="px-2 py-1 text-left text-white/60">이름</th>
                      <th className="px-2 py-1 text-left text-white/60">연락처</th>
                      <th className="px-2 py-1 text-left text-white/60">이메일</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-white/5">
                    {supplierStaff.map((staff) => (
                      <tr key={staff.idx}>
                        <td className="px-2 py-1 text-white">{staff.name}</td>
                        <td className="px-2 py-1 text-white/70">{staff.tel}</td>
                        <td className="px-2 py-1 text-white/70 truncate max-w-[100px]" title={staff.email}>{staff.email}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              ) : (
                <div className="text-center text-white/30 text-xs py-2">담당자 정보 없음</div>
              )}
            </div>
          </div>

          {/* 최근 입고내역 */}
          <div className="glass-effect rounded-xl p-3 flex-1 min-h-0 flex flex-col">
            <div className="flex items-center gap-2 mb-2 border-b border-white/10 pb-2">
              <TrendingDown className="w-4 h-4 text-green-400" />
              <h3 className="text-sm font-medium text-white">최근 입고내역</h3>
            </div>
            <div className="flex-1 overflow-auto">
              {detailLoading ? (
                <div className="text-center py-2">
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white/50 mx-auto"></div>
                </div>
              ) : incomingHistory.length > 0 ? (
                <table className="w-full text-xs">
                  <thead className="bg-white/5 sticky top-0">
                    <tr>
                      <th className="px-1 py-1 text-left text-white/60">일자</th>
                      <th className="px-1 py-1 text-left text-white/60">요청자</th>
                      <th className="px-1 py-1 text-right text-white/60">수량</th>
                      <th className="px-1 py-1 text-right text-white/60">금액</th>
                      <th className="px-1 py-1 text-left text-white/60">상태</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-white/5">
                    {incomingHistory.map((h) => (
                      <tr key={h.idx}>
                        <td className="px-1 py-1 text-white/80 whitespace-nowrap">{h.date}</td>
                        <td className="px-1 py-1 text-white/70 truncate max-w-[50px]" title={h.request}>{h.request}</td>
                        <td className="px-1 py-1 text-white text-right">{h.qty.toLocaleString()}</td>
                        <td className="px-1 py-1 text-white text-right">{h.price.toLocaleString()}</td>
                        <td className="px-1 py-1 text-white/70">{h.state}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              ) : (
                <div className="text-center text-white/30 text-xs py-2">입고내역 없음</div>
              )}
            </div>
          </div>

          {/* 발주내역 */}
          <div className="glass-effect rounded-xl p-3 flex-1 min-h-0 flex flex-col">
            <div className="flex items-center gap-2 mb-2 border-b border-white/10 pb-2">
              <ShoppingCart className="w-4 h-4 text-blue-400" />
              <h3 className="text-sm font-medium text-white">발주내역</h3>
            </div>
            <div className="flex-1 overflow-auto">
              {detailLoading ? (
                <div className="text-center py-2">
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white/50 mx-auto"></div>
                </div>
              ) : orderHistory.length > 0 ? (
                <table className="w-full text-xs">
                  <thead className="bg-white/5 sticky top-0">
                    <tr>
                      <th className="px-1 py-1 text-left text-white/60">일자</th>
                      <th className="px-1 py-1 text-left text-white/60">요청자</th>
                      <th className="px-1 py-1 text-right text-white/60">수량</th>
                      <th className="px-1 py-1 text-right text-white/60">금액</th>
                      <th className="px-1 py-1 text-left text-white/60">상태</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-white/5">
                    {orderHistory.map((h) => (
                      <tr key={h.idx}>
                        <td className="px-1 py-1 text-white/80 whitespace-nowrap">{h.date}</td>
                        <td className="px-1 py-1 text-white/70 truncate max-w-[50px]" title={h.request}>{h.request}</td>
                        <td className="px-1 py-1 text-white text-right">{h.qty.toLocaleString()}</td>
                        <td className="px-1 py-1 text-white text-right">{h.price.toLocaleString()}</td>
                        <td className="px-1 py-1 text-white/70">{h.state}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              ) : (
                <div className="text-center text-white/30 text-xs py-2">발주내역 없음</div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 편집 다이얼로그 */}
      <ItemEditDialog
        item={selectedItem}
        isOpen={dialogOpen}
        onClose={() => {
          setDialogOpen(false);
          setSelectedItem(null);
        }}
        onSave={handleSave}
        onDelete={handleDelete}
      />
    </div>
  );
}
