import { useState, useEffect, useCallback } from 'react';
import type { RescueOpsItem } from '@interfaces/rescue/RescueInterface';
import { fetchRescueOps } from '../../services/rescueApi';

export function RescueListView() {
  const [opsList, setOpsList] = useState<RescueOpsItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');

  const loadOps = useCallback(async () => {
    setLoading(true);
    try {
      const items = await fetchRescueOps({ search: searchTerm || undefined });
      setOpsList(items);
    } catch (err) {
      console.error('[rescue] 구난 작전 목록 조회 실패:', err);
    } finally {
      setLoading(false);
    }
  }, [searchTerm]);

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

  const getStatusLabel = (sttsCd: string) => {
    switch (sttsCd) {
      case 'ACTIVE':
        return { label: '대응중', color: 'var(--color-danger)' };
      case 'STANDBY':
        return { label: '대기', color: 'var(--color-warning)' };
      case 'COMPLETED':
        return { label: '종료', color: 'var(--color-success)' };
      default:
        return { label: sttsCd, color: 'var(--fg-disabled)' };
    }
  };

  const getTypeLabel = (tpCd: string) => {
    const map: Record<string, string> = {
      collision: '충돌',
      grounding: '좌초',
      turning: '선회',
      capsizing: '전복',
      sharpTurn: '급선회',
      flooding: '침수',
      sinking: '침몰',
    };
    return map[tpCd] ?? tpCd;
  };

  return (
    <div className="flex flex-col flex-1 overflow-hidden">
      <div className="px-5 py-4 flex items-center justify-between border-b border-stroke">
        <span className="text-title-3 font-bold font-korean">긴급구난 사고 목록</span>
        <div className="flex gap-2 items-center">
          <input
            type="text"
            placeholder="선박명 / 사고번호 검색..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="px-3 py-1.5 bg-bg-base border border-stroke rounded-md text-fg-sub font-korean text-label-2 w-[200px] outline-none focus:border-[var(--color-accent)]"
          />
          <button
            className="rounded-sm text-label-2 font-semibold cursor-pointer text-color-accent px-3.5 py-1.5 font-korean"
            style={{
              border: '1px solid rgba(6,182,212,.3)',
              background: 'rgba(6,182,212,.08)',
            }}
          >
            + 신규 사고 등록
          </button>
        </div>
      </div>
      <div className="flex-1 overflow-y-auto px-5 pb-4">
        {loading ? (
          <div className="text-center py-20 text-fg-disabled text-title-3">로딩 중...</div>
        ) : opsList.length === 0 ? (
          <div className="text-center py-20 text-fg-disabled text-title-3">
            구난 작전 데이터가 없습니다.
          </div>
        ) : (
          <table className="w-full border-collapse text-label-2 mt-3">
            <thead>
              <tr className="bg-bg-card border-b border-stroke">
                {['상태', '사고번호', '선박명', '사고유형', '발생일시', '위치', '인명'].map((h) => (
                  <th
                    key={h}
                    className="py-2 px-2.5 text-left font-korean font-semibold text-fg-disabled text-label-2"
                  >
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {opsList.map((r) => {
                const status = getStatusLabel(r.sttsCd);
                return (
                  <tr
                    key={r.rescueOpsSn}
                    className="border-b border-stroke hover:bg-bg-surface-hover cursor-pointer"
                  >
                    <td className="py-2 px-2.5">
                      <span
                        className="px-2 py-0.5 rounded-xl text-caption font-bold"
                        style={{
                          background: `color-mix(in srgb, ${status.color} 15%, transparent)`,
                          color: status.color,
                        }}
                      >
                        {status.label}
                      </span>
                    </td>
                    <td className="py-2 px-2.5 font-mono text-color-accent font-semibold">
                      {r.opsCd}
                    </td>
                    <td className="py-2 px-2.5 font-korean text-fg font-semibold">{r.vesselNm}</td>
                    <td className="py-2 px-2.5 font-korean">{getTypeLabel(r.acdntTpCd)}</td>
                    <td className="py-2 px-2.5 font-mono text-fg-disabled">
                      {r.regDtm ? new Date(r.regDtm).toLocaleString('ko-KR') : '—'}
                    </td>
                    <td className="py-2 px-2.5 font-mono text-fg-disabled text-label-2">
                      {r.locDc ?? '—'}
                    </td>
                    <td className="py-2 px-2.5 font-mono">
                      {r.survivors ?? 0}/{r.totalCrew ?? 0}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
