import { useState, useEffect } from 'react';
import { fetchOrganizations, fetchOrganizationDetail } from '../services/assetsApi';
import type { AssetOrgCompat } from '../services/assetsApi';
import AssetMap from './AssetMap';

function AssetManagement() {
  const [viewMode, setViewMode] = useState<'list' | 'map'>('list');
  const [organizations, setOrganizations] = useState<AssetOrgCompat[]>([]);
  const [selectedOrg, setSelectedOrg] = useState<AssetOrgCompat | null>(null);
  const [detailTab, setDetailTab] = useState<'equip' | 'material' | 'contact'>('equip');
  const [regionFilter, setRegionFilter] = useState('all');
  const [searchTerm, setSearchTerm] = useState('');
  const [typeFilterVal, setTypeFilterVal] = useState('all');
  const [equipFilter, setEquipFilter] = useState('all');
  const [currentPage, setCurrentPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const pageSize = 15;

  // API에서 기관 목록 로드
  useEffect(() => {
    let cancelled = false;
    fetchOrganizations()
      .then((data) => {
        if (cancelled) return;
        setOrganizations(data);
        if (data.length > 0) setSelectedOrg(data[0]);
      })
      .catch((err) => console.error('[assets] 기관 목록 로드 실패:', err))
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  // 기관 선택 시 상세 조회 (장비/담당자)
  const handleSelectOrg = async (org: AssetOrgCompat) => {
    setSelectedOrg(org);
    try {
      const detail = await fetchOrganizationDetail(org.id);
      setSelectedOrg(detail);
    } catch {
      // 상세 조회 실패 시 기본 정보 유지
    }
  };

  const filtered = organizations.filter((o) => {
    if (regionFilter !== 'all' && !o.jurisdiction.includes(regionFilter)) return false;
    if (typeFilterVal !== 'all' && o.type !== typeFilterVal) return false;
    if (equipFilter !== 'all') {
      const equipMap: Record<string, (org: AssetOrgCompat) => boolean> = {
        vessel: (org) => org.vessel > 0,
        skimmer: (org) => org.skimmer > 0,
        pump: (org) => org.pump > 0,
        vehicle: (org) => org.vehicle > 0,
        sprayer: (org) => org.sprayer > 0,
      };
      if (equipMap[equipFilter] && !equipMap[equipFilter](o)) return false;
    }
    if (searchTerm && !o.name.includes(searchTerm) && !o.address.includes(searchTerm)) return false;
    return true;
  });

  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const safePage = Math.min(currentPage, totalPages);
  const paged = filtered.slice((safePage - 1) * pageSize, safePage * pageSize);

  // 필터 변경 시 첫 페이지로
  useEffect(() => {
    setCurrentPage(1); // eslint-disable-line react-hooks/set-state-in-effect -- 필터 변경 시 페이지 리셋
  }, [regionFilter, typeFilterVal, equipFilter, searchTerm]);

  const regionShort = (j: string) => {
    if (j.includes('중부')) return '중부청';
    if (j.includes('서해')) return '서해청';
    if (j.includes('남해')) return '남해청';
    if (j.includes('동해')) return '동해청';
    if (j.includes('중앙')) return '중특단';
    return '제주청';
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-fg-disabled text-body-2 font-korean">
          방제자산 데이터를 불러오는 중...
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full">
      {/* View Switcher & Filters */}
      <div className="flex items-center justify-between mb-3 pb-3 border-b border-stroke">
        <div className="flex gap-1">
          <button
            onClick={() => setViewMode('list')}
            className={`px-3 py-1.5 text-label-2 font-semibold rounded-sm font-korean transition-colors ${
              viewMode === 'list'
                ? 'bg-[color-mix(in_srgb,var(--color-accent)_15%,transparent)] text-color-accent border border-[color-mix(in_srgb,var(--color-accent)_30%,transparent)]'
                : 'border border-stroke text-fg-sub hover:bg-bg-surface-hover'
            }`}
          >
            📋 방제자산리스트
          </button>
          <button
            onClick={() => setViewMode('map')}
            className={`px-3 py-1.5 text-label-2 font-semibold rounded-sm font-korean transition-colors ${
              viewMode === 'map'
                ? 'bg-[color-mix(in_srgb,var(--color-accent)_15%,transparent)] text-color-accent border border-[color-mix(in_srgb,var(--color-accent)_30%,transparent)]'
                : 'border border-stroke text-fg-sub hover:bg-bg-surface-hover'
            }`}
          >
            🗺 지도 보기
          </button>
        </div>
        <div className="flex gap-1.5 items-center">
          <input
            type="text"
            placeholder="기관명 검색..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="prd-i w-40 py-1.5 px-2.5"
          />
          <select
            value={regionFilter}
            onChange={(e) => setRegionFilter(e.target.value)}
            className="prd-i w-[100px] py-1.5 px-2"
          >
            <option value="all">전체 관할</option>
            <option value="남해">남해청</option>
            <option value="서해">서해청</option>
            <option value="중부">중부청</option>
            <option value="동해">동해청</option>
            <option value="제주">제주청</option>
          </select>
          <select
            value={typeFilterVal}
            onChange={(e) => setTypeFilterVal(e.target.value)}
            className="prd-i w-[100px] py-1.5 px-2"
          >
            <option value="all">전체 유형</option>
            <option value="해경관할">해경관할</option>
            <option value="해경경찰서">해경경찰서</option>
            <option value="파출소">파출소</option>
            <option value="관련기관">관련기관</option>
            <option value="해양환경공단">해양환경공단</option>
            <option value="업체">업체</option>
            <option value="지자체">지자체</option>
            <option value="기름저장시설">기름저장시설</option>
            <option value="정유사">정유사</option>
            <option value="해군">해군</option>
            <option value="기타">기타</option>
          </select>
          <select
            value={equipFilter}
            onChange={(e) => setEquipFilter(e.target.value)}
            className="prd-i w-[100px] py-1.5 px-2"
          >
            <option value="all">전체 장비</option>
            <option value="vessel">방제선</option>
            <option value="skimmer">유회수기</option>
            <option value="pump">이송펌프</option>
            <option value="vehicle">방제차량</option>
            <option value="sprayer">살포장치</option>
          </select>
        </div>
      </div>

      {viewMode === 'list' ? (
        /* ── LIST VIEW ── */
        <div className="flex-1 border border-stroke rounded-md overflow-hidden flex flex-col">
          <div className="flex-1">
            <table className="w-full text-left" style={{ tableLayout: 'fixed' }}>
              <colgroup>
                <col style={{ width: '3.5%' }} />
                <col style={{ width: '7%' }} />
                <col style={{ width: '7%' }} />
                <col style={{ width: '12%' }} />
                <col />
                <col style={{ width: '8%' }} />
                <col style={{ width: '7%' }} />
                <col style={{ width: '7%' }} />
                <col style={{ width: '5%' }} />
                <col style={{ width: '5%' }} />
                <col style={{ width: '5%' }} />
              </colgroup>
              <thead>
                <tr className="border-b border-stroke bg-bg-base">
                  {[
                    '번호',
                    '유형',
                    '관할청',
                    '기관명',
                    '주소',
                    '방제선',
                    '유회수기',
                    '이송펌프',
                    '방제차량',
                    '살포장치',
                    '총자산',
                  ].map((h, i) => {
                    const equipColMap: Record<string, number> = {
                      vessel: 5,
                      skimmer: 6,
                      pump: 7,
                      vehicle: 8,
                      sprayer: 9,
                    };
                    const isHighlight = equipFilter !== 'all' && equipColMap[equipFilter] === i;
                    return (
                      <th
                        key={i}
                        className={`px-2.5 py-2.5 text-caption font-bold font-korean border-b border-stroke ${[0, 5, 6, 7, 8, 9, 10].includes(i) ? 'text-center' : ''} ${isHighlight ? 'text-color-accent bg-[color-mix(in_srgb,var(--color-accent)_5%,transparent)]' : 'text-fg-sub'}`}
                      >
                        {h}
                      </th>
                    );
                  })}
                </tr>
              </thead>
              <tbody>
                {paged.map((org, idx) => (
                  <tr
                    key={org.id}
                    className={`border-b border-stroke hover:bg-white/[0.02] cursor-pointer transition-colors`}
                    onClick={() => {
                      handleSelectOrg(org);
                      setViewMode('map');
                    }}
                  >
                    <td className="px-2.5 py-2 text-center font-mono text-caption">
                      {(safePage - 1) * pageSize + idx + 1}
                    </td>
                    <td className="px-2.5 py-2">
                      <span className="text-caption text-color-accent font-korean">{org.type}</span>
                    </td>
                    <td className="px-2.5 py-2 text-caption font-korean">
                      {regionShort(org.jurisdiction)}
                    </td>
                    <td className="px-2.5 py-2 text-caption text-fg-sub font-korean cursor-pointer truncate">
                      {org.name}
                    </td>
                    <td className="px-2.5 py-2 text-caption text-fg-disabled font-korean truncate">
                      {org.address}
                    </td>
                    <td
                      className={`px-2.5 py-2 text-center font-mono text-caption ${equipFilter === 'vessel' ? 'text-color-accent bg-[color-mix(in_srgb,var(--color-accent)_5%,transparent)]' : ''}`}
                    >
                      {org.vessel}척
                    </td>
                    <td
                      className={`px-2.5 py-2 text-center font-mono text-caption ${equipFilter === 'skimmer' ? 'text-color-accent bg-[color-mix(in_srgb,var(--color-accent)_5%,transparent)]' : ''}`}
                    >
                      {org.skimmer}대
                    </td>
                    <td
                      className={`px-2.5 py-2 text-center font-mono text-caption ${equipFilter === 'pump' ? 'text-color-accent bg-[color-mix(in_srgb,var(--color-accent)_5%,transparent)]' : ''}`}
                    >
                      {org.pump}대
                    </td>
                    <td
                      className={`px-2.5 py-2 text-center font-mono text-caption ${equipFilter === 'vehicle' ? 'text-color-accent bg-[color-mix(in_srgb,var(--color-accent)_5%,transparent)]' : ''}`}
                    >
                      {org.vehicle}대
                    </td>
                    <td
                      className={`px-2.5 py-2 text-center font-mono text-caption ${equipFilter === 'sprayer' ? 'text-color-accent bg-[color-mix(in_srgb,var(--color-accent)_5%,transparent)]' : ''}`}
                    >
                      {org.sprayer}대
                    </td>
                    <td className="px-2.5 py-2 text-center text-fg-sub font-mono text-caption">
                      {org.totalAssets}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Totals Summary */}
          <div className="flex items-center justify-end gap-4 px-4 py-2 border-t border-stroke bg-bg-base/80">
            <span className="text-caption text-fg-disabled font-korean font-semibold mr-auto">
              합계 ({filtered.length}개 기관)
            </span>
            {[
              {
                key: 'vessel',
                label: '방제선',
                value: filtered.reduce((s, o) => s + o.vessel, 0),
                unit: '척',
              },
              {
                key: 'skimmer',
                label: '유회수기',
                value: filtered.reduce((s, o) => s + o.skimmer, 0),
                unit: '대',
              },
              {
                key: 'pump',
                label: '이송펌프',
                value: filtered.reduce((s, o) => s + o.pump, 0),
                unit: '대',
              },
              {
                key: 'vehicle',
                label: '방제차량',
                value: filtered.reduce((s, o) => s + o.vehicle, 0),
                unit: '대',
              },
              {
                key: 'sprayer',
                label: '살포장치',
                value: filtered.reduce((s, o) => s + o.sprayer, 0),
                unit: '대',
              },
              {
                key: 'total',
                label: '총자산',
                value: filtered.reduce((s, o) => s + o.totalAssets, 0),
                unit: '',
              },
            ].map((t) => {
              const isActive = equipFilter === t.key || t.key === 'total';
              return (
                <div
                  key={t.key}
                  className={`flex items-center gap-1 px-1.5 py-0.5 rounded ${equipFilter === t.key ? 'bg-[color-mix(in_srgb,var(--color-accent)_10%,transparent)]' : ''}`}
                >
                  <span
                    className={`text-caption font-korean ${isActive ? 'text-color-accent' : 'text-fg-disabled'}`}
                  >
                    {t.label}
                  </span>
                  <span
                    className={`text-caption font-mono font-bold ${isActive ? 'text-color-accent' : 'text-fg'}`}
                  >
                    {t.value.toLocaleString()}
                    {t.unit}
                  </span>
                </div>
              );
            })}
          </div>

          {/* Pagination */}
          <div className="flex items-center justify-center gap-4 px-4 py-2.5 border-t border-stroke bg-bg-base">
            <span className="text-caption text-fg-disabled font-korean">
              전체 <span className="font-semibold text-fg-sub">{filtered.length}</span>건 중{' '}
              <span className="font-semibold text-fg-sub">
                {(safePage - 1) * pageSize + 1}-{Math.min(safePage * pageSize, filtered.length)}
              </span>
            </span>
            <div className="flex items-center gap-1">
              <button
                onClick={() => setCurrentPage(1)}
                disabled={safePage <= 1}
                className="px-1.5 py-1 text-caption rounded border border-stroke bg-bg-card text-fg-sub disabled:opacity-30 hover:bg-bg-surface-hover transition-colors cursor-pointer disabled:cursor-default"
              >
                «
              </button>
              <button
                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                disabled={safePage <= 1}
                className="px-1.5 py-1 text-caption rounded border border-stroke bg-bg-card text-fg-sub disabled:opacity-30 hover:bg-bg-surface-hover transition-colors cursor-pointer disabled:cursor-default"
              >
                ‹
              </button>
              {Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
                <button
                  key={p}
                  onClick={() => setCurrentPage(p)}
                  className={`w-6 h-6 text-caption font-bold rounded transition-colors cursor-pointer ${
                    p === safePage
                      ? 'bg-[color-mix(in_srgb,var(--color-accent)_20%,transparent)] text-color-accent border border-[color-mix(in_srgb,var(--color-accent)_40%,transparent)]'
                      : 'border border-stroke bg-bg-card text-fg-disabled hover:bg-bg-surface-hover'
                  }`}
                >
                  {p}
                </button>
              ))}
              <button
                onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                disabled={safePage >= totalPages}
                className="px-1.5 py-1 text-caption rounded border border-stroke bg-bg-card text-fg-sub disabled:opacity-30 hover:bg-bg-surface-hover transition-colors cursor-pointer disabled:cursor-default"
              >
                ›
              </button>
              <button
                onClick={() => setCurrentPage(totalPages)}
                disabled={safePage >= totalPages}
                className="px-1.5 py-1 text-caption rounded border border-stroke bg-bg-card text-fg-sub disabled:opacity-30 hover:bg-bg-surface-hover transition-colors cursor-pointer disabled:cursor-default"
              >
                »
              </button>
            </div>
          </div>
        </div>
      ) : (
        /* ── MAP VIEW ── */
        <div className="flex-1 flex overflow-hidden rounded-md border border-stroke">
          {/* Map */}
          <div className="flex-1 relative overflow-hidden">
            <AssetMap
              organizations={filtered}
              selectedOrg={selectedOrg!}
              onSelectOrg={handleSelectOrg}
              regionFilter={regionFilter}
              onRegionFilterChange={setRegionFilter}
            />
          </div>

          {/* Right Detail Panel */}
          {selectedOrg && (
            <aside className="w-[340px] min-w-[340px] bg-bg-surface border-l border-stroke flex flex-col">
              {/* Header */}
              <div className="p-4 border-b border-stroke">
                <div className="text-body-2 font-bold mb-1 font-korean">{selectedOrg.name}</div>
                <div className="text-label-2 text-fg-sub font-semibold font-korean mb-1">
                  {selectedOrg.type} · {regionShort(selectedOrg.jurisdiction)} · {selectedOrg.area}
                </div>
                <div className="text-label-2 text-fg-disabled font-korean">
                  {selectedOrg.address}
                </div>
              </div>

              {/* Sub-tabs */}
              <div className="flex border-b border-stroke">
                {(['equip', 'material', 'contact'] as const).map((t) => (
                  <button
                    key={t}
                    onClick={() => setDetailTab(t)}
                    className={`flex-1 py-2.5 text-center text-label-2 font-semibold font-korean border-b-2 transition-colors cursor-pointer ${
                      detailTab === t
                        ? 'text-color-accent border-color-accent'
                        : 'text-fg-disabled border-transparent hover:text-fg-sub'
                    }`}
                  >
                    {t === 'equip' ? '장비' : t === 'material' ? '자재' : '연락처'}
                  </button>
                ))}
              </div>

              {/* Content */}
              <div
                className="flex-1 overflow-y-auto p-3.5 scrollbar-thin"
                style={{ scrollbarGutter: 'stable' }}
              >
                {/* Summary */}
                <div className="grid grid-cols-3 gap-1.5 mb-3">
                  {[
                    { value: `${selectedOrg.vessel}척`, label: '방제선' },
                    { value: `${selectedOrg.skimmer}대`, label: '유회수기' },
                    { value: String(selectedOrg.totalAssets), label: '총 자산' },
                  ].map((s, i) => (
                    <div
                      key={i}
                      className="bg-bg-card border border-stroke rounded-sm p-2.5 text-center"
                    >
                      <div className="text-lg font-bold text-color-accent font-mono">{s.value}</div>
                      <div className="text-caption text-fg-disabled mt-0.5 font-korean">
                        {s.label}
                      </div>
                    </div>
                  ))}
                </div>

                {detailTab === 'equip' && (
                  <div className="flex flex-col gap-1">
                    {selectedOrg.equipment.length > 0 ? (
                      selectedOrg.equipment.map((cat, ci) => {
                        const unitMap: Record<string, string> = {
                          방제선: '척',
                          유회수기: '대',
                          비치크리너: '대',
                          이송펌프: '대',
                          방제차량: '대',
                          해안운반차: '대',
                          고압세척기: '대',
                          저압세척기: '대',
                          동력분무기: '대',
                          유량계측기: '대',
                          방제창고: '개소',
                          발전기: '대',
                          현장지휘소: '개',
                          지원장비: '대',
                          장비부품: '개',
                          경비함정방제: '대',
                          살포장치: '대',
                        };
                        const unit = unitMap[cat.category] || '개';
                        return (
                          <div
                            key={ci}
                            className="flex items-center justify-between px-2.5 py-2 bg-bg-card border border-stroke rounded-sm hover:bg-bg-surface-hover transition-colors"
                          >
                            <span className="text-label-2 font-semibold flex items-center gap-1.5 font-korean">
                              {cat.icon} {cat.category}
                            </span>
                            <span className="text-label-2 font-bold font-mono">
                              <span className="text-color-accent">{cat.count}</span>
                              <span className="text-fg-disabled font-normal ml-0.5">{unit}</span>
                            </span>
                          </div>
                        );
                      })
                    ) : (
                      <div className="text-center text-fg-disabled text-caption py-8 font-korean">
                        상세 장비 데이터가 없습니다.
                      </div>
                    )}
                  </div>
                )}

                {detailTab === 'material' && (
                  <div className="flex flex-col gap-1.5">
                    {[
                      ['방제선', `${selectedOrg.vessel}척`],
                      ['유회수기', `${selectedOrg.skimmer}대`],
                      ['이송펌프', `${selectedOrg.pump}대`],
                      ['방제차량', `${selectedOrg.vehicle}대`],
                      ['살포장치', `${selectedOrg.sprayer}대`],
                      ['총 자산', `${selectedOrg.totalAssets}건`],
                    ].map(([k, v], i) => (
                      <div
                        key={i}
                        className="flex justify-between px-2.5 py-2 bg-bg-base rounded text-label-2"
                      >
                        <span className="text-fg-disabled font-korean">{k}</span>
                        <span className="font-mono font-semibold text-fg">{v}</span>
                      </div>
                    ))}
                  </div>
                )}

                {detailTab === 'contact' && (
                  <div className="flex flex-col gap-2">
                    {/* 기관 기본 정보 */}
                    <div className="bg-bg-card border border-stroke rounded-sm p-3">
                      <div className="text-caption font-bold text-fg-disabled mb-2 font-korean">
                        기관 정보
                      </div>
                      {[
                        ['기관명', selectedOrg.name],
                        ['유형', selectedOrg.type],
                        ['관할청', selectedOrg.jurisdiction],
                        ['주소', selectedOrg.address],
                        ...(selectedOrg.phone ? [['대표 연락처', selectedOrg.phone]] : []),
                      ].map(([k, v], j) => (
                        <div
                          key={j}
                          className="flex justify-between py-1.5 text-label-2 border-b border-stroke last:border-b-0"
                        >
                          <span className="text-fg-disabled font-korean shrink-0 mr-2">{k}</span>
                          <span
                            className={`text-fg text-right ${k === '대표 연락처' ? 'font-mono font-semibold text-color-accent' : 'font-korean'}`}
                          >
                            {v}
                          </span>
                        </div>
                      ))}
                    </div>

                    {/* 담당자 목록 */}
                    {selectedOrg.contacts.length > 0 && (
                      <div className="bg-bg-card border border-stroke rounded-sm p-3">
                        <div className="text-caption font-bold text-fg-disabled mb-2 font-korean">
                          담당자
                        </div>
                        {selectedOrg.contacts.map((c, i) => (
                          <div key={i} className="mb-2.5 last:mb-0">
                            {[
                              ['직책', c.role],
                              ['담당자', c.name],
                              ['연락처', c.phone],
                            ]
                              .filter(([, v]) => v)
                              .map(([k, v], j) => (
                                <div
                                  key={j}
                                  className="flex justify-between py-1.5 text-label-2 border-b border-stroke last:border-b-0"
                                >
                                  <span className="text-fg-disabled font-korean">{k}</span>
                                  <span
                                    className={`text-fg ${k === '연락처' ? 'font-mono font-semibold text-color-accent' : 'font-korean'}`}
                                  >
                                    {v}
                                  </span>
                                </div>
                              ))}
                            {i < selectedOrg.contacts.length - 1 && (
                              <div className="border-t border-stroke mt-1" />
                            )}
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* Bottom Actions */}
              {/* <div className="p-3.5 border-t border-stroke flex gap-2">
                <button className="flex-1 py-2.5 rounded-sm text-caption font-semibold font-korean text-white bg-color-accent border-none cursor-pointer hover:opacity-90 transition-opacity">
                  📥 다운로드
                </button>
                <button className="flex-1 py-2.5 rounded-sm text-caption font-semibold font-korean bg-bg-card border border-stroke text-fg-sub cursor-pointer hover:bg-bg-surface-hover transition-colors">
                  ✏ 수정
                </button>
              </div> */}
            </aside>
          )}
        </div>
      )}
    </div>
  );
}

export default AssetManagement;
