import { useState } from 'react';
import type { GscAccidentListItem } from '@interfaces/prediction/PredictionInterface';
import type { AccidentType } from '@/types/rescue/RescueType';
import { accidentTypes } from '../RescueView';

export function LeftPanel({
  activeType,
  onTypeChange,
  incidents,
  selectedAcdnt,
  onSelectAcdnt,
}: {
  activeType: AccidentType;
  onTypeChange: (t: AccidentType) => void;
  incidents: GscAccidentListItem[];
  selectedAcdnt: GscAccidentListItem | null;
  onSelectAcdnt: (item: GscAccidentListItem | null) => void;
}) {
  const [acdntName, setAcdntName] = useState('');
  const [acdntDate, setAcdntDate] = useState('');
  const [acdntTime, setAcdntTime] = useState('');
  const [acdntLat, setAcdntLat] = useState('');
  const [acdntLon, setAcdntLon] = useState('');
  const [showList, setShowList] = useState(false);

  // 사고 선택 시 필드 자동 채움
  const handlePickIncident = (item: GscAccidentListItem) => {
    onSelectAcdnt(item);
    setAcdntName(item.pollNm);
    if (item.pollDate) {
      const [d, t] = item.pollDate.split('T');
      if (d) {
        const [y, m, day] = d.split('-');
        setAcdntDate(`${y}. ${m}. ${day}.`);
      }
      if (t) {
        const [hhStr, mmStr] = t.split(':');
        const hh = parseInt(hhStr, 10);
        const ampm = hh >= 12 ? '오후' : '오전';
        const hh12 = String(hh % 12 || 12).padStart(2, '0');
        setAcdntTime(`${ampm} ${hh12}:${mmStr}`);
      }
    }
    if (item.lat != null) setAcdntLat(String(item.lat));
    if (item.lon != null) setAcdntLon(String(item.lon));
    setShowList(false);
  };

  return (
    <div className="w-[208px] min-w-[208px] bg-bg-base border-r border-stroke flex flex-col overflow-y-auto scrollbar-thin p-2 gap-0.5">
      {/* ── 사고 기본정보 ── */}
      <div className="text-caption font-bold text-fg-disabled font-korean mb-0.5 tracking-wider">
        사고 기본정보
      </div>

      {/* 사고명 직접 입력 */}
      <input
        type="text"
        placeholder="사고명 직접 입력"
        value={acdntName}
        onChange={(e) => {
          setAcdntName(e.target.value);
          if (selectedAcdnt) onSelectAcdnt(null);
        }}
        className="w-full px-2 py-1.5 text-caption bg-bg-card border border-stroke rounded font-korean placeholder:text-fg-disabled/50 text-fg focus:border-[rgba(6,182,212,0.5)] focus:outline-none"
      />

      {/* 또는 사고 리스트에서 선택 */}
      <div className="relative">
        <button
          onClick={() => setShowList(!showList)}
          className="w-full px-2 py-1.5 text-caption bg-bg-card border border-stroke rounded font-korean text-left cursor-pointer hover:border-[var(--stroke-light)] flex items-center justify-between"
        >
          <span className={selectedAcdnt ? 'text-fg' : 'text-fg-disabled/50'}>
            {selectedAcdnt ? selectedAcdnt.pollNm : '또는 사고 리스트에서 선택'}
          </span>
          <span className="text-fg-disabled text-[10px]">{showList ? '▲' : '▼'}</span>
        </button>
        {showList && (
          <div className="absolute left-0 right-0 top-full mt-0.5 z-30 bg-bg-card border border-stroke rounded shadow-lg max-h-[200px] overflow-y-auto scrollbar-thin">
            {incidents.length === 0 && (
              <div className="px-2 py-3 text-caption text-fg-disabled text-center font-korean">
                사고 데이터 없음
              </div>
            )}
            {incidents.map((item) => (
              <button
                key={item.acdntMngNo}
                onClick={() => handlePickIncident(item)}
                className="w-full text-left px-2 py-1.5 text-caption font-korean hover:bg-bg-surface cursor-pointer border-b border-stroke last:border-b-0"
              >
                <div className="text-fg font-semibold truncate">{item.pollNm}</div>
                <div className="text-fg-disabled text-[10px]">
                  {item.pollDate ? item.pollDate.replace('T', ' ') : '-'}
                </div>
              </button>
            ))}
          </div>
        )}
      </div>

      {/* 사고 발생 일시 */}
      <div className="text-[10px] text-fg-disabled font-korean mt-1">사고 발생 일시</div>
      <div className="flex gap-1">
        <input
          type="text"
          placeholder="2026. 04. 11."
          value={acdntDate}
          onChange={(e) => setAcdntDate(e.target.value)}
          className="flex-1 min-w-0 px-1.5 py-1 text-caption bg-bg-card border border-stroke rounded font-mono text-fg placeholder:text-fg-disabled/50 focus:border-[rgba(6,182,212,0.5)] focus:outline-none"
        />
        <input
          type="text"
          placeholder="오후 03:42"
          value={acdntTime}
          onChange={(e) => setAcdntTime(e.target.value)}
          className="flex-1 min-w-0 px-1.5 py-1 text-caption bg-bg-card border border-stroke rounded font-mono text-fg placeholder:text-fg-disabled/50 focus:border-[rgba(6,182,212,0.5)] focus:outline-none"
        />
      </div>

      {/* 위도 / 경도 */}
      <div className="flex gap-1 mt-0.5">
        <input
          type="text"
          placeholder="위도"
          value={acdntLat}
          onChange={(e) => setAcdntLat(e.target.value)}
          className="flex-1 min-w-0 px-1.5 py-1 text-caption bg-bg-card border border-stroke rounded font-mono text-fg placeholder:text-fg-disabled/50 focus:border-[rgba(6,182,212,0.5)] focus:outline-none"
        />
        <input
          type="text"
          placeholder="경도"
          value={acdntLon}
          onChange={(e) => setAcdntLon(e.target.value)}
          className="flex-1 min-w-0 px-1.5 py-1 text-caption bg-bg-card border border-stroke rounded font-mono text-fg placeholder:text-fg-disabled/50 focus:border-[rgba(6,182,212,0.5)] focus:outline-none"
        />
        <button
          className="shrink-0 px-1.5 py-1 text-[10px] font-bold rounded cursor-pointer"
          style={{
            background: 'rgba(239,68,68,0.15)',
            color: 'var(--color-danger)',
            border: '1px solid rgba(239,68,68,0.3)',
          }}
        >
          지도
        </button>
      </div>
      <div className="text-[10px] text-fg-disabled font-korean text-center mb-1">
        지도에서 위치를 선택하세요
      </div>

      {/* 구분선 */}
      <div className="border-t border-stroke my-1" />

      {/* 사고유형 제목 */}
      <div className="text-caption font-bold text-fg-disabled font-korean mb-0.5 tracking-wider">
        사고 유형 (INCIDENT TYPE)
      </div>

      {/* 사고유형 버튼 */}
      {accidentTypes.map((t) => (
        <button
          key={t.id}
          onClick={() => onTypeChange(t.id)}
          className={`flex items-center gap-2 w-full text-left px-2.5 py-[7px] rounded-md border transition-all cursor-pointer ${
            activeType === t.id
              ? 'bg-[rgba(6,182,212,0.1)] border-[rgba(6,182,212,0.35)]'
              : 'bg-bg-card border-stroke hover:border-[var(--stroke-light)] hover:bg-bg-surface-hover'
          }`}
        >
          <span className="text-label-1">{t.icon}</span>
          <div>
            <div
              className={`text-label-2 font-bold font-korean ${activeType === t.id ? 'text-color-accent' : 'text-fg'}`}
            >
              {t.label} ({t.eng})
            </div>
            <div className="text-caption text-fg-disabled font-korean mt-px">{t.desc}</div>
          </div>
        </button>
      ))}

      {/* 긴급 경고 */}
      <div className="text-caption font-bold text-fg-disabled font-korean mt-2.5 mb-1">
        긴급 경고 (CRITICAL ALERTS)
      </div>
      <div className="py-1.5 px-2.5 border-l-2 border-l-[var(--color-danger)] rounded-r text-caption text-fg-disabled font-korean">
        GM 위험 수준 — 전복 위험
      </div>
      <div className="py-1.5 px-2.5 border-l-2 border-l-[var(--color-danger)] rounded-r text-caption text-fg-disabled font-korean">
        승선자 5명 미확인
      </div>
      <div className="py-1.5 px-2.5 border-l-2 border-l-[var(--color-danger)] rounded-r text-caption text-fg-disabled font-korean">
        유류 유출 감지 - 방제 필요
      </div>
      <div className="py-1.5 px-2.5 border-l-2 border-l-[var(--color-danger)] rounded-r text-caption text-fg-disabled font-korean">
        종강도 한계치 88% 접근
      </div>

      {/* CCTV 피드 */}
      <div className="w-full aspect-[4/3] bg-bg-base border border-stroke rounded-md flex items-center justify-center relative overflow-hidden mt-1.5 flex-shrink-0">
        <div
          className="absolute inset-0"
          style={{
            background: 'repeating-linear-gradient(0deg, rgba(255,0,0,.03), transparent 2px)',
          }}
        />
        <div className="text-caption text-[rgba(255,60,60,0.35)] font-mono">CCTV FEED #1</div>
        <div className="absolute top-1 left-1.5 text-caption text-[rgba(255,60,60,0.5)] font-mono">
          ● REC
        </div>
      </div>
    </div>
  );
}
