import { useState } from 'react';

type SourceType = 'satellite' | 'cctv' | 'drone' | 'ais';

interface SourceConfig {
  id: SourceType;
  label: string;
  icon: string;
  color: string;
  desc: string;
}

const SOURCES: SourceConfig[] = [
  {
    id: 'satellite',
    label: '위성영상',
    icon: '🛰',
    color: 'var(--color-accent)',
    desc: 'KOMPSAT-3A / Sentinel SAR 수신 영상',
  },
  {
    id: 'cctv',
    label: 'CCTV',
    icon: '📹',
    color: 'var(--color-info)',
    desc: 'KHOA / KBS 해안 CCTV 스냅샷',
  },
  {
    id: 'drone',
    label: '드론',
    icon: '🛸',
    color: 'var(--color-success)',
    desc: '정밀 촬영 / 열화상 이미지',
  },
  {
    id: 'ais',
    label: 'AIS',
    icon: '🚢',
    color: 'var(--color-warning)',
    desc: '선박 위치·항적·MMSI 궤적',
  },
];

interface ChangeRecord {
  id: string;
  area: string;
  type: string;
  date1: string;
  time1: string;
  date2: string;
  time2: string;
  severity: '심각' | '보통' | '낮음';
  detail: string;
  sources: SourceType[];
  crossRef?: string;
  /** 각 정보원별 AS-IS 시점 요약 */
  asIsDetail: Partial<Record<SourceType, string>>;
  /** 각 정보원별 현재 시점 요약 */
  nowDetail: Partial<Record<SourceType, string>>;
}

export function ChangeDetectPanel() {
  const [layers, setLayers] = useState<Record<SourceType, boolean>>({
    satellite: true,
    cctv: true,
    drone: true,
    ais: true,
  });
  const [sourceFilter, setSourceFilter] = useState<SourceType | 'all'>('all');
  const [selectedChange, setSelectedChange] = useState<string | null>(null);

  const toggleLayer = (id: SourceType) => setLayers((prev) => ({ ...prev, [id]: !prev[id] }));
  const activeCount = Object.values(layers).filter(Boolean).length;

  const changes: ChangeRecord[] = [
    {
      id: 'CHG-001',
      area: '여수항 북측 해안',
      type: '선박 이동',
      date1: '03-14',
      time1: '14:00',
      date2: '03-16',
      time2: '14:23',
      severity: '보통',
      detail: '정박 선박 3척 → 7척 (증가)',
      sources: ['satellite', 'ais', 'cctv'],
      crossRef: 'AIS MMSI 440123456 외 3척 신규 입항 — 위성+CCTV 동시 확인',
      asIsDetail: {
        satellite: '정박 선박 3척 식별',
        ais: 'MMSI 3건 정박 상태',
        cctv: '여수 오동도 CCTV 정상',
      },
      nowDetail: {
        satellite: '선박 7척 식별 (4척 증가)',
        ais: 'MMSI 7건 (신규 4건 입항)',
        cctv: '여수 오동도 CCTV 선박 증가 확인',
      },
    },
    {
      id: 'CHG-002',
      area: '제주 서귀포 해상',
      type: '유막 확산',
      date1: '03-15',
      time1: '10:30',
      date2: '03-16',
      time2: '14:23',
      severity: '심각',
      detail: '유막 면적 2.1km² → 4.8km² (확산)',
      sources: ['satellite', 'drone', 'cctv', 'ais'],
      crossRef: '4개 정보원 교차확인 — 유막 남동 방향 확산 일치',
      asIsDetail: {
        satellite: 'SAR 유막 2.1km² 탐지',
        drone: '열화상 유막 경계 포착',
        cctv: '서귀포 카메라 해면 이상 없음',
        ais: '인근 유조선 1척 정박',
      },
      nowDetail: {
        satellite: 'SAR 유막 4.8km² 확산',
        drone: '열화상 유막 남동 2.7km 확대',
        cctv: '서귀포 카메라 해면 변색 감지',
        ais: '유조선 이탈, 방제선 2척 진입',
      },
    },
    {
      id: 'CHG-003',
      area: '부산항 외항',
      type: '방제장비 배치',
      date1: '03-10',
      time1: '09:00',
      date2: '03-16',
      time2: '14:23',
      severity: '낮음',
      detail: '부유식 오일펜스 신규 배치 확인',
      sources: ['drone', 'cctv'],
      crossRef: 'CCTV 부산항 #204 + 드론 정밀 촬영 일치',
      asIsDetail: { drone: '오일펜스 미배치', cctv: '부산 민락항 CCTV 해상 장비 없음' },
      nowDetail: { drone: '오일펜스 300m 배치 확인', cctv: '부산 민락항 CCTV 오일펜스 포착' },
    },
    {
      id: 'CHG-004',
      area: '통영 해역 남측',
      type: '미식별 선박',
      date1: '03-13',
      time1: '22:00',
      date2: '03-16',
      time2: '14:23',
      severity: '보통',
      detail: 'AIS 미송출 선박 2척 위성 포착',
      sources: ['satellite', 'ais'],
      crossRef: 'AIS 미등록 — 위성 SAR 반사 신호로 탐지, 불법 조업 의심',
      asIsDetail: { satellite: '해역 내 선박 신호 없음', ais: '등록 선박 0척' },
      nowDetail: { satellite: 'SAR 반사 2건 포착 (선박 추정)', ais: 'MMSI 미수신 — 미식별 선박' },
    },
    {
      id: 'CHG-005',
      area: '인천 연안부두',
      type: '야간 이상징후',
      date1: '03-15',
      time1: '03:42',
      date2: '03-16',
      time2: '03:45',
      severity: '심각',
      detail: 'CCTV 야간 유출 의심 + AIS 정박선 이탈',
      sources: ['cctv', 'ais'],
      crossRef: 'KBS CCTV #9981 03:42 해면 반사 이상 → AIS 03:45 정박선 이탈 연계',
      asIsDetail: { cctv: '인천 연안부두 CCTV 야간 정상', ais: '정박선 5척 정상 정박' },
      nowDetail: {
        cctv: '03:42 해면 반사광 이상 감지',
        ais: '03:45 정박선 1척 이탈 (MMSI 441987654)',
      },
    },
    {
      id: 'CHG-006',
      area: '마라도 주변 해역',
      type: '해안선 변화',
      date1: '03-12',
      time1: '11:00',
      date2: '03-16',
      time2: '11:15',
      severity: '낮음',
      detail: '해안 퇴적물 분포 변경 감지',
      sources: ['satellite', 'drone'],
      crossRef: '위성 다분광 + 드론 정밀 촬영 퇴적 방향 확인',
      asIsDetail: { satellite: '해안선 퇴적 분포 기준점', drone: '미촬영' },
      nowDetail: { satellite: '퇴적 남서 방향 이동 감지', drone: '정밀 촬영으로 퇴적 경계 확인' },
    },
  ];

  const severityStyle = (s: '심각' | '보통' | '낮음') => {
    if (s === '심각')
      return {
        background: 'color-mix(in srgb, var(--color-danger) 12%, transparent)',
        color: 'var(--color-danger)',
        border: '1px solid color-mix(in srgb, var(--color-danger) 25%, transparent)',
      };
    if (s === '보통')
      return {
        background: 'color-mix(in srgb, var(--color-caution) 12%, transparent)',
        color: 'var(--color-caution)',
        border: '1px solid color-mix(in srgb, var(--color-caution) 25%, transparent)',
      };
    return {
      background: 'color-mix(in srgb, var(--color-success) 12%, transparent)',
      color: 'var(--color-success)',
      border: '1px solid color-mix(in srgb, var(--color-success) 25%, transparent)',
    };
  };

  const sourceStyle = (src: SourceConfig, active = true) =>
    active
      ? { background: `${src.color}18`, color: src.color, border: `1px solid ${src.color}40` }
      : {
          background: 'var(--bg-card)',
          color: 'var(--fg-disabled)',
          border: '1px solid var(--stroke-default)',
          opacity: 0.5,
        };

  const filteredChanges =
    sourceFilter === 'all' ? changes : changes.filter((c) => c.sources.includes(sourceFilter));

  return (
    <div>
      {/* 레이어 토글 바 */}
      <div className="flex items-center gap-3 mb-4">
        <div className="text-caption font-bold font-korean text-fg-disabled shrink-0">
          오버레이 레이어
        </div>
        <div className="flex gap-1.5">
          {SOURCES.map((s) => (
            <button
              key={s.id}
              onClick={() => toggleLayer(s.id)}
              className="px-2.5 py-1.5 rounded text-caption font-bold font-korean cursor-pointer border transition-all"
              style={sourceStyle(s, layers[s.id])}
            >
              <span className="mr-1">{layers[s.id] ? '◉' : '○'}</span>
              {/* {s.icon}  */}
              {s.label}
            </button>
          ))}
        </div>
        <div className="text-caption text-fg-disabled font-mono ml-auto">
          {activeCount}/4 레이어 활성
        </div>
      </div>

      {/* AS-IS / 현재 시점 비교 뷰 */}
      <div className="grid grid-cols-2 gap-4 mb-4" style={{ minHeight: 400 }}>
        {/* AS-IS 시점 */}
        <div className="bg-bg-elevated border border-stroke rounded-md overflow-hidden">
          <div
            className="flex items-center justify-between px-4 py-2.5 border-b border-stroke"
            style={{ background: 'rgba(6,182,212,.05)' }}
          >
            <div className="flex items-center gap-2">
              <span
                className="text-label-2 font-bold font-korean"
                style={{ color: 'var(--color-accent)' }}
              >
                AS-IS
              </span>
              <span
                className="text-caption px-1.5 py-0.5 rounded font-bold"
                style={{
                  background: 'rgba(6,182,212,.12)',
                  color: 'var(--color-accent)',
                  border: '1px solid rgba(6,182,212,.25)',
                }}
              >
                과거 시점
              </span>
            </div>
            <div className="flex items-center gap-2">
              <input
                type="date"
                defaultValue="2026-03-14"
                className="text-caption font-mono px-2 py-1 rounded border outline-none"
                style={{
                  background: 'var(--bg-card)',
                  borderColor: 'var(--stroke-default)',
                  color: 'var(--fg-sub)',
                }}
              />
              <input
                type="time"
                defaultValue="14:00"
                className="text-caption font-mono px-2 py-1 rounded border outline-none"
                style={{
                  background: 'var(--bg-card)',
                  borderColor: 'var(--stroke-default)',
                  color: 'var(--fg-sub)',
                }}
              />
            </div>
          </div>
          {/* 활성 레이어 표시 */}
          {/* <div
            className="flex gap-1 px-3 py-2 border-b"
            style={{ borderColor: 'rgba(255,255,255,.04)' }}
          >
            {SOURCES.filter((s) => layers[s.id]).map((s) => (
              <span
                key={s.id}
                className="px-1.5 py-0.5 rounded text-caption font-bold"
                style={sourceStyle(s)}
              >
                {s.icon} {s.label}
              </span>
            ))}
            {activeCount === 0 && (
              <span className="text-caption text-fg-disabled font-korean">레이어를 선택하세요</span>
            )}
          </div> */}
          {/* 지도 플레이스홀더 */}
          <div
            className="flex items-center justify-center text-fg-disabled"
            style={{ height: 320 }}
          >
            <div className="text-center">
              <div className="flex justify-center gap-2 text-2xl mb-3 opacity-30">
                {SOURCES.filter((s) => layers[s.id]).map((s) => (
                  <span key={s.id}>{s.icon}</span>
                ))}
              </div>
              <div className="text-label-2 font-korean text-fg-disabled">
                과거 시점 복합 오버레이
              </div>
              <div className="text-caption text-fg-disabled mt-1">
                {SOURCES.filter((s) => layers[s.id])
                  .map((s) => s.label)
                  .join(' + ')}{' '}
                통합 표시
              </div>
            </div>
          </div>
        </div>

        {/* 현재 시점 */}
        <div className="bg-bg-elevated border border-stroke rounded-md overflow-hidden">
          <div
            className="flex items-center justify-between px-4 py-2.5 border-b border-stroke"
            style={{ background: 'rgba(6,182,212,.05)' }}
          >
            <div className="flex items-center gap-2">
              <span
                className="text-label-2 font-bold font-korean"
                style={{ color: 'var(--color-accent)' }}
              >
                현재
              </span>
              <span
                className="text-caption px-1.5 py-0.5 rounded font-bold"
                style={{
                  background: 'rgba(6,182,212,.12)',
                  color: 'var(--color-accent)',
                  border: '1px solid rgba(6,182,212,.25)',
                }}
              >
                NOW
              </span>
            </div>
            <span className="text-caption text-fg-disabled font-mono">2026-03-16 14:23</span>
          </div>
          {/* 활성 레이어 표시 */}
          {/* <div
            className="flex gap-1 px-3 py-2 border-b"
            style={{ borderColor: 'rgba(255,255,255,.04)' }}
          >
            {SOURCES.filter((s) => layers[s.id]).map((s) => (
              <span
                key={s.id}
                className="px-1.5 py-0.5 rounded text-caption font-bold"
                style={sourceStyle(s)}
              >
                {s.icon} {s.label}
              </span>
            ))}
            {activeCount === 0 && (
              <span className="text-caption text-fg-disabled font-korean">레이어를 선택하세요</span>
            )}
          </div> */}
          {/* 지도 플레이스홀더 */}
          <div
            className="flex items-center justify-center text-fg-disabled"
            style={{ height: 320 }}
          >
            <div className="text-center">
              <div className="flex justify-center gap-2 text-2xl mb-3 opacity-30">
                {SOURCES.filter((s) => layers[s.id]).map((s) => (
                  <span key={s.id}>{s.icon}</span>
                ))}
              </div>
              <div className="text-label-2 font-korean text-fg-disabled">
                현재 시점 복합 오버레이
              </div>
              <div className="text-caption text-fg-disabled mt-1">
                {SOURCES.filter((s) => layers[s.id])
                  .map((s) => s.label)
                  .join(' + ')}{' '}
                실시간 통합
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 복합 변화 감지 목록 */}
      <div className="bg-bg-elevated border border-stroke rounded-md overflow-hidden">
        <div className="flex items-center justify-between px-4 py-3 border-b border-stroke">
          <div className="text-label-2 font-bold font-korean text-fg">
            🔄 복합 변화 감지 타임라인
          </div>
          <div className="flex items-center gap-2">
            <div className="flex gap-1">
              <button
                onClick={() => setSourceFilter('all')}
                className="px-2 py-0.5 rounded text-caption font-bold font-korean cursor-pointer border transition-colors"
                style={
                  sourceFilter === 'all'
                    ? {
                        background: 'rgba(6,182,212,.08)',
                        borderColor: 'rgba(6,182,212,.3)',
                        color: 'var(--color-accent)',
                      }
                    : {
                        background: 'var(--bg-card)',
                        borderColor: 'var(--stroke-default)',
                        color: 'var(--fg-disabled)',
                      }
                }
              >
                전체
              </button>
              {SOURCES.map((s) => (
                <button
                  key={s.id}
                  onClick={() => setSourceFilter(s.id)}
                  className="px-2 py-0.5 rounded text-caption font-bold font-korean cursor-pointer border transition-colors"
                  style={
                    sourceFilter === s.id
                      ? {
                          background: 'rgba(6,182,212,.08)',
                          borderColor: 'rgba(6,182,212,.3)',
                          color: 'var(--color-accent)',
                        }
                      : {
                          background: 'var(--bg-card)',
                          borderColor: 'var(--stroke-default)',
                          color: 'var(--fg-disabled)',
                        }
                  }
                >
                  {s.label}
                </button>
              ))}
            </div>
            <div className="text-caption text-fg-disabled font-mono">
              {filteredChanges.length}건
            </div>
          </div>
        </div>

        {/* 데이터 행 */}
        {filteredChanges.map((c) => {
          const isOpen = selectedChange === c.id;
          return (
            <div key={c.id} className="border-b" style={{ borderColor: 'rgba(255,255,255,.04)' }}>
              {/* 요약 행 */}
              <div
                onClick={() => setSelectedChange(isOpen ? null : c.id)}
                className="grid gap-0 px-4 py-3 items-center hover:bg-bg-surface-hover/30 transition-colors cursor-pointer"
                style={{
                  gridTemplateColumns: '52px 1fr 200px 150px 52px',
                  background: isOpen ? 'rgba(6,182,212,.04)' : undefined,
                }}
              >
                <div className="text-caption font-mono text-fg-disabled">{c.id}</div>
                <div>
                  <div className="flex items-center gap-2">
                    <span className="text-label-2 font-semibold text-fg font-korean">{c.area}</span>
                    <span
                      className="text-caption font-korean"
                      style={{ color: 'var(--fg-disabled)' }}
                    >
                      {c.type}
                    </span>
                  </div>
                  <div className="text-caption text-fg-disabled font-korean mt-0.5">{c.detail}</div>
                </div>
                <div className="flex flex-wrap gap-1">
                  {c.sources.map((sid) => {
                    const cfg = SOURCES.find((s) => s.id === sid)!;
                    return (
                      <span
                        key={sid}
                        className="px-1.5 py-0.5 rounded text-caption text-fg"
                        style={{
                          background: 'transparent',
                          border: `1px solid color-mix(in srgb, ${cfg.color} 40%, transparent)`,
                          color: `${cfg.color}`,
                        }}
                      >
                        {cfg.label}
                      </span>
                    );
                  })}
                </div>
                <div className="text-caption font-mono">
                  <span className="text-fg">
                    {c.date1} {c.time1}
                  </span>
                  <span className="text-fg-disabled mx-1">→</span>
                  <span className="text-fg">
                    {c.date2} {c.time2}
                  </span>
                </div>
                <div>
                  <span
                    className="px-1.5 py-0.5 rounded text-caption font-bold font-korean"
                    style={severityStyle(c.severity)}
                  >
                    {c.severity}
                  </span>
                </div>
              </div>

              {/* 펼침: 정보원별 AS-IS → 현재 상세 */}
              {isOpen && (
                <div className="px-4 pb-3 pt-1" style={{ background: 'rgba(6,182,212,.02)' }}>
                  {/* 교차검증 */}
                  {c.crossRef && (
                    <div
                      className="mb-3 px-3 py-2 rounded text-caption font-korean"
                      style={{
                        background: 'rgba(6,182,212,.06)',
                        border: '1px solid rgba(6,182,212,.15)',
                        color: 'var(--fg-sub)',
                      }}
                    >
                      <span className="font-bold" style={{ color: 'var(--color-accent)' }}>
                        교차검증
                      </span>{' '}
                      {c.crossRef}
                    </div>
                  )}
                  {/* 정보원별 비교 그리드 */}
                  <div className="grid gap-2">
                    <div
                      className="grid gap-0 px-3 py-1.5"
                      style={{ gridTemplateColumns: '90px 1fr 1fr' }}
                    >
                      <div className="text-caption font-bold text-fg-disabled font-korean">
                        정보원
                      </div>
                      <div className="text-caption font-bold font-korean text-fg">
                        AS-IS ({c.date1} {c.time1})
                      </div>
                      <div className="text-caption font-bold font-korean text-fg">
                        현재 ({c.date2} {c.time2})
                      </div>
                    </div>
                    {c.sources.map((sid) => {
                      const cfg = SOURCES.find((s) => s.id === sid)!;
                      return (
                        <div
                          key={sid}
                          className="grid gap-0 px-3 py-2 rounded"
                          style={{
                            gridTemplateColumns: '90px 1fr 1fr',
                            background: `${cfg.color}06`,
                            border: `1px solid ${cfg.color}15`,
                          }}
                        >
                          <div className="flex items-center gap-1.5">
                            <span
                              className="text-caption font-bold px-1.5 py-0.5 rounded"
                              style={sourceStyle(cfg)}
                            >
                              {cfg.icon} {cfg.label}
                            </span>
                          </div>
                          <div className="text-caption font-korean text-fg-disabled">
                            {c.asIsDetail[sid] || '-'}
                          </div>
                          <div className="text-caption font-korean text-fg">
                            {c.nowDetail[sid] || '-'}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}
