import { useState, useEffect, useCallback } from 'react';
import { type OilSpillReportData, type ReportType } from './OilSpillReportTemplate';
import {
  templateTypes,
  type TemplateType,
  ANALYSIS_SEP,
  ANALYSIS_FIELD_ORDER,
} from './reportTypes';
import { saveReport } from '../services/reportsApi';

interface TemplateEditPageProps {
  reportType: ReportType;
  initialData: OilSpillReportData;
  onSave: () => void;
  onBack: () => void;
}

// ── Textarea-type keys that map to analysis field ──────────
const ANALYSIS_KEYS = new Set([
  'initialResponse',
  'futurePlan',
  'responseStatus',
  'suggestions',
  'spreadSummary',
  'responseDetail',
  'damageReport',
  'futurePlanDetail',
  'spreadAnalysis',
  'analysis',
]);

function getInitialValue(key: string, data: OilSpillReportData, reportType: ReportType): string {
  if (key.startsWith('incident.')) {
    const field = key.slice('incident.'.length) as keyof OilSpillReportData['incident'];
    return (data.incident as Record<string, string>)[field] ?? '';
  }
  if (key === 'author') return data.author;
  if (ANALYSIS_KEYS.has(key)) {
    const fields = ANALYSIS_FIELD_ORDER[reportType];
    if (fields) {
      const idx = fields.indexOf(key);
      if (idx < 0) return '';
      const analysis = data.analysis || '';
      if (!analysis.includes(ANALYSIS_SEP)) {
        // 레거시 데이터: 첫 번째 필드에만 배분
        return idx === 0 ? analysis : '';
      }
      const parts = analysis.split(ANALYSIS_SEP);
      return parts[idx] || '';
    }
    return data.analysis || '';
  }
  if (key.startsWith('__')) return '';
  return '';
}

function buildAnalysis(reportType: ReportType, formData: Record<string, string>): string {
  const fields = ANALYSIS_FIELD_ORDER[reportType];
  if (fields) {
    return fields.map((k) => formData[k] || '').join(ANALYSIS_SEP);
  }
  switch (reportType) {
    case '예측보고서':
      return formData['analysis'] || '';
    default:
      return '';
  }
}

// ── Section content renderer ────────────────────────────────
interface SectionBlockProps {
  section: TemplateType['sections'][number];
  getVal: (key: string) => string;
  setVal: (key: string, val: string) => void;
}

function SectionBlock({ section, getVal, setVal }: SectionBlockProps) {
  return (
    <div
      style={{
        position: 'relative',
        background: 'var(--bg-surface)',
        padding: '28px 36px',
        marginBottom: '16px',
        borderRadius: '6px',
        border: '1px solid var(--stroke-default)',
      }}
    >
      <div
        style={{
          position: 'absolute',
          top: 10,
          right: 16,
          fontSize: 'var(--font-size-caption)',
          color: 'var(--fg-disabled)',
          fontWeight: 600,
        }}
      >
        해양오염방제지원시스템
      </div>

      {/* Section header */}
      <div
        style={{
          background: 'color-mix(in srgb, var(--color-accent) 12%, transparent)',
          color: 'var(--color-accent)',
          padding: '8px 16px',
          fontSize: 'var(--font-size-title-4)',
          fontWeight: 700,
          marginBottom: '16px',
          borderRadius: '4px',
          border: '1px solid color-mix(in srgb, var(--color-accent) 20%, transparent)',
        }}
      >
        {section.title}
      </div>

      {/* Fields table */}
      <table
        style={{
          width: '100%',
          tableLayout: 'fixed',
          borderCollapse: 'collapse',
          fontSize: 'var(--font-size-caption)',
        }}
      >
        <colgroup>
          <col style={{ width: '160px' }} />
          <col />
        </colgroup>
        <tbody>
          {section.fields.map((field, fIdx) => {
            // ── Read-only auto-calculated keys ──
            if (field.key.startsWith('__')) {
              return (
                <tr key={fIdx}>
                  <td
                    colSpan={2}
                    style={{ border: '1px solid var(--stroke-default)', padding: '12px 14px' }}
                  >
                    <span
                      style={{
                        color: 'var(--fg-disabled)',
                        fontStyle: 'italic',
                        fontSize: 'var(--font-size-caption)',
                      }}
                    >
                      {section.title} — 자동 계산 데이터 (확인 전용)
                    </span>
                  </td>
                </tr>
              );
            }

            // ── Textarea (no label = full-width, or labeled textarea) ──
            if (field.type === 'textarea' || !field.label) {
              return (
                <tr key={fIdx}>
                  {field.label && (
                    <td
                      style={{
                        background: 'var(--bg-card)',
                        border: '1px solid var(--stroke-default)',
                        padding: '8px 14px',
                        fontWeight: 600,
                        color: 'var(--fg-sub)',
                        verticalAlign: 'top',
                        fontSize: 'var(--font-size-caption)',
                      }}
                    >
                      {field.label}
                    </td>
                  )}
                  <td
                    colSpan={field.label ? 1 : 2}
                    style={{ border: '1px solid var(--stroke-default)', padding: '6px' }}
                  >
                    <textarea
                      value={getVal(field.key)}
                      onChange={(e) => setVal(field.key, e.target.value)}
                      placeholder="내용을 입력하세요..."
                      style={{
                        width: '100%',
                        minHeight: '110px',
                        background: 'var(--bg-base)',
                        border: '1px solid var(--stroke-light)',
                        borderRadius: '3px',
                        padding: '8px 12px',
                        fontSize: 'var(--font-size-label-1)',
                        outline: 'none',
                        resize: 'vertical',
                        color: 'var(--fg-default)',
                      }}
                    />
                  </td>
                </tr>
              );
            }

            // ── Checkbox group ──
            if (field.type === 'checkbox-group' && field.options) {
              return (
                <tr key={fIdx}>
                  <td
                    style={{
                      background: 'var(--bg-card)',
                      border: '1px solid var(--stroke-default)',
                      padding: '8px 14px',
                      fontWeight: 600,
                      color: 'var(--fg-sub)',
                      verticalAlign: 'middle',
                      fontSize: 'var(--font-size-caption)',
                    }}
                  >
                    {field.label}
                  </td>
                  <td style={{ border: '1px solid var(--stroke-default)', padding: '8px 14px' }}>
                    <div style={{ display: 'flex', gap: '16px', flexWrap: 'wrap' }}>
                      {field.options.map((opt) => (
                        <label
                          key={opt}
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: '6px',
                            fontSize: 'var(--font-size-caption)',
                            color: 'var(--fg-sub)',
                            cursor: 'pointer',
                          }}
                        >
                          <input type="checkbox" style={{ accentColor: 'var(--color-accent)' }} />
                          {opt}
                        </label>
                      ))}
                    </div>
                  </td>
                </tr>
              );
            }

            // ── Default: text input ──
            return (
              <tr key={fIdx}>
                <td
                  style={{
                    background: 'var(--bg-card)',
                    border: '1px solid var(--stroke-default)',
                    padding: '8px 14px',
                    fontWeight: 600,
                    color: 'var(--fg-sub)',
                    verticalAlign: 'middle',
                    fontSize: 'var(--font-size-caption)',
                  }}
                >
                  {field.label}
                </td>
                <td style={{ border: '1px solid var(--stroke-default)', padding: '5px 10px' }}>
                  <input
                    value={getVal(field.key)}
                    onChange={(e) => setVal(field.key, e.target.value)}
                    placeholder={`${field.label} 입력`}
                    style={{
                      width: '100%',
                      background: 'transparent',
                      border: 'none',
                      fontSize: 'var(--font-size-caption)',
                      outline: 'none',
                      color: 'var(--fg-default)',
                      padding: '2px 0',
                    }}
                  />
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// ── Main Component ──────────────────────────────────────────
export default function TemplateEditPage({
  reportType,
  initialData,
  onSave,
  onBack,
}: TemplateEditPageProps) {
  const template = templateTypes.find((t) => t.id === reportType)!;
  const sections = template.sections;

  const buildInitialFormData = useCallback(() => {
    const init: Record<string, string> = {};
    sections.forEach((sec) => {
      sec.fields.forEach((f) => {
        init[f.key] = getInitialValue(f.key, initialData, reportType);
      });
    });
    return init;
  }, [sections, initialData, reportType]);

  const [formData, setFormData] = useState<Record<string, string>>(buildInitialFormData);
  const [title, setTitle] = useState(initialData.title || '');
  const [currentPage, setCurrentPage] = useState(0);
  const [viewMode, setViewMode] = useState<'page' | 'all'>('page');

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setFormData(buildInitialFormData());
    setTitle(initialData.title || '');
    setCurrentPage(0);
  }, [initialData, buildInitialFormData]);

  const getVal = (key: string) => formData[key] ?? '';
  const setVal = (key: string, val: string) => setFormData((p) => ({ ...p, [key]: val }));

  const handleSave = useCallback(async () => {
    const updated: OilSpillReportData = {
      ...initialData,
      title:
        title ||
        formData['incident.name'] ||
        `${reportType} ${new Date().toLocaleDateString('ko-KR')}`,
      author: formData['author'] || initialData.author,
      analysis: buildAnalysis(reportType, formData),
      incident: {
        ...initialData.incident,
        name: formData['incident.name'] ?? initialData.incident.name,
        writeTime: formData['incident.writeTime'] ?? initialData.incident.writeTime,
        shipName: formData['incident.shipName'] ?? initialData.incident.shipName,
        occurTime: formData['incident.occurTime'] ?? initialData.incident.occurTime,
        location: formData['incident.location'] ?? initialData.incident.location,
        lat: formData['incident.lat'] ?? initialData.incident.lat,
        lon: formData['incident.lon'] ?? initialData.incident.lon,
        accidentType: formData['incident.accidentType'] ?? initialData.incident.accidentType,
        pollutant: formData['incident.pollutant'] ?? initialData.incident.pollutant,
        spillAmount: formData['incident.spillAmount'] ?? initialData.incident.spillAmount,
        depth: formData['incident.depth'] ?? initialData.incident.depth,
        seabed: formData['incident.seabed'] ?? initialData.incident.seabed,
        agent: formData['agent'] ?? initialData.incident.agent,
      },
    };
    try {
      await saveReport(updated);
      onSave();
    } catch (err) {
      console.error('[reports] 저장 오류:', err);
      alert('보고서 저장 중 오류가 발생했습니다.');
    }
  }, [formData, title, initialData, reportType, onSave]);

  return (
    <div className="flex flex-col h-full overflow-hidden bg-bg-base">
      {/* ── Toolbar ── */}
      <div className="flex items-center justify-between px-5 py-3 border-b border-stroke bg-bg-surface shrink-0 flex-wrap gap-2">
        <div className="flex items-center gap-3">
          <button
            onClick={onBack}
            className="text-label-1 font-semibold text-fg-sub hover:text-fg transition-colors whitespace-nowrap"
          >
            ← 돌아가기
          </button>
          <input
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="보고서 제목 입력"
            className="text-title-1 font-bold bg-bg-base border border-[var(--stroke-light)] rounded px-2.5 py-1 outline-none w-[380px] max-w-[480px]"
          />
          <span
            className="px-2.5 py-[3px] text-label-2 font-semibold rounded border whitespace-nowrap"
            style={{
              background: 'color-mix(in srgb, var(--color-warning) 15%, transparent)',
              color: 'var(--color-warning)',
              borderColor: 'color-mix(in srgb, var(--color-warning) 30%, transparent)',
            }}
          >
            편집 중
          </span>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setViewMode('all')}
            className="px-3.5 py-1.5 text-label-2 font-semibold rounded cursor-pointer"
            style={{
              border:
                viewMode === 'all'
                  ? '1px solid var(--color-accent)'
                  : '1px solid var(--stroke-default)',
              background:
                viewMode === 'all'
                  ? 'color-mix(in srgb, var(--color-accent) 10%, transparent)'
                  : 'var(--bg-elevated)',
              color: viewMode === 'all' ? 'var(--color-accent)' : 'var(--fg-disabled)',
            }}
          >
            전체 보기
          </button>
          <button
            onClick={() => setViewMode('page')}
            className="px-3.5 py-1.5 text-label-2 font-semibold rounded cursor-pointer"
            style={{
              border:
                viewMode === 'page'
                  ? '1px solid var(--color-accent)'
                  : '1px solid var(--stroke-default)',
              background:
                viewMode === 'page'
                  ? 'color-mix(in srgb, var(--color-accent) 10%, transparent)'
                  : 'var(--bg-elevated)',
              color: viewMode === 'page' ? 'var(--color-accent)' : 'var(--fg-disabled)',
            }}
          >
            페이지별
          </button>
          <button
            onClick={handleSave}
            className="px-4 py-1.5 text-label-2 font-bold rounded cursor-pointer border border-color-success bg-[color-mix(in_srgb,var(--color-success)_15%,transparent)] text-color-success"
          >
            저장
          </button>
          <button
            onClick={() => window.print()}
            className="px-3.5 py-1.5 text-label-2 font-semibold rounded cursor-pointer border border-[var(--color-danger)] bg-[color-mix(in_srgb,var(--color-danger)_10%,transparent)] text-color-danger"
          >
            인쇄 / PDF
          </button>
        </div>
      </div>

      {/* ── Section Tabs (page mode) ── */}
      {viewMode === 'page' && (
        <div className="flex gap-1 px-5 py-2 border-b border-stroke bg-bg-surface flex-wrap shrink-0">
          {sections.map((sec, i) => (
            <button
              key={i}
              onClick={() => setCurrentPage(i)}
              className="px-3 py-1.5 text-label-2 font-semibold rounded cursor-pointer"
              style={{
                border:
                  currentPage === i
                    ? '1px solid var(--color-accent)'
                    : '1px solid var(--stroke-default)',
                background:
                  currentPage === i
                    ? 'color-mix(in srgb, var(--color-accent) 15%, transparent)'
                    : 'transparent',
                color: currentPage === i ? 'var(--color-accent)' : 'var(--fg-disabled)',
              }}
            >
              {sec.title}
            </button>
          ))}
        </div>
      )}

      {/* ── Content ── */}
      <div className="flex-1 overflow-auto px-5 py-5">
        <div id="report-print-area" className="w-full">
          {viewMode === 'all' ? (
            sections.map((sec, i) => (
              <SectionBlock key={i} section={sec} getVal={getVal} setVal={setVal} />
            ))
          ) : (
            <div>
              <SectionBlock section={sections[currentPage]} getVal={getVal} setVal={setVal} />

              {/* ── Pagination ── */}
              <div className="flex justify-center items-center gap-3 mt-5">
                <button
                  onClick={() => setCurrentPage((p) => Math.max(0, p - 1))}
                  disabled={currentPage === 0}
                  className="px-5 py-2 text-label-1 font-semibold rounded border border-stroke bg-bg-elevated cursor-pointer"
                  style={{
                    color: currentPage === 0 ? 'var(--fg-disabled)' : 'var(--fg-default)',
                    opacity: currentPage === 0 ? 0.4 : 1,
                  }}
                >
                  이전
                </button>
                <span className="px-4 py-2 text-label-1 text-fg-sub">
                  {currentPage + 1} / {sections.length}
                </span>
                <button
                  onClick={() => setCurrentPage((p) => Math.min(sections.length - 1, p + 1))}
                  disabled={currentPage === sections.length - 1}
                  className="px-5 py-2 text-label-1 font-semibold rounded cursor-pointer"
                  style={{
                    border: '1px solid var(--color-accent)',
                    background: 'color-mix(in srgb, var(--color-accent) 10%, transparent)',
                    color:
                      currentPage === sections.length - 1
                        ? 'var(--fg-disabled)'
                        : 'var(--color-accent)',
                    opacity: currentPage === sections.length - 1 ? 0.4 : 1,
                  }}
                >
                  다음
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
