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(--bg1)',
      padding: '28px 36px',
      marginBottom: '16px',
      borderRadius: '6px',
      border: '1px solid var(--bd)',
    }}>
      <div style={{ position: 'absolute', top: 10, right: 16, fontSize: '9px', color: 'var(--t3)', fontWeight: 600 }}>
        해양오염방제지원시스템
      </div>

      {/* Section header */}
      <div style={{
        background: 'rgba(6,182,212,0.12)', color: 'var(--cyan)', padding: '8px 16px',
        fontSize: '13px', fontWeight: 700, marginBottom: '16px', borderRadius: '4px',
        border: '1px solid rgba(6,182,212,0.2)',
      }}>
        {section.title}
      </div>

      {/* Fields table */}
      <table style={{ width: '100%', tableLayout: 'fixed', borderCollapse: 'collapse', fontSize: '11px' }}>
        <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(--bd)', padding: '12px 14px' }}
                  >
                    <span style={{ color: 'var(--t3)', fontStyle: 'italic', fontSize: '11px' }}>
                      {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(--bg3)', border: '1px solid var(--bd)',
                      padding: '8px 14px', fontWeight: 600, color: 'var(--t2)',
                      verticalAlign: 'top', fontSize: '11px',
                    }}>
                      {field.label}
                    </td>
                  )}
                  <td
                    colSpan={field.label ? 1 : 2}
                    style={{ border: '1px solid var(--bd)', padding: '6px' }}
                  >
                    <textarea
                      value={getVal(field.key)}
                      onChange={e => setVal(field.key, e.target.value)}
                      placeholder="내용을 입력하세요..."
                      style={{
                        width: '100%', minHeight: '110px',
                        background: 'var(--bg0)', border: '1px solid var(--bdL)',
                        borderRadius: '3px', padding: '8px 12px',
                        fontSize: '12px', outline: 'none', resize: 'vertical',
                        color: 'var(--t1)', fontFamily: 'inherit',
                      }}
                    />
                  </td>
                </tr>
              );
            }

            // ── Checkbox group ──
            if (field.type === 'checkbox-group' && field.options) {
              return (
                <tr key={fIdx}>
                  <td style={{
                    background: 'var(--bg3)', border: '1px solid var(--bd)',
                    padding: '8px 14px', fontWeight: 600, color: 'var(--t2)',
                    verticalAlign: 'middle', fontSize: '11px',
                  }}>
                    {field.label}
                  </td>
                  <td style={{ border: '1px solid var(--bd)', 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: '11px', color: 'var(--t2)', cursor: 'pointer',
                        }}>
                          <input type="checkbox" style={{ accentColor: '#06b6d4' }} />
                          {opt}
                        </label>
                      ))}
                    </div>
                  </td>
                </tr>
              );
            }

            // ── Default: text input ──
            return (
              <tr key={fIdx}>
                <td style={{
                  background: 'var(--bg3)', border: '1px solid var(--bd)',
                  padding: '8px 14px', fontWeight: 600, color: 'var(--t2)',
                  verticalAlign: 'middle', fontSize: '11px',
                }}>
                  {field.label}
                </td>
                <td style={{ border: '1px solid var(--bd)', 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: '11px', outline: 'none', color: 'var(--t1)', 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-0">

      {/* ── Toolbar ── */}
      <div className="flex items-center justify-between px-5 py-3 border-b border-border bg-bg-1 shrink-0 flex-wrap gap-2">
        <div className="flex items-center gap-3">
          <button
            onClick={onBack}
            className="text-[12px] font-semibold text-text-2 hover:text-text-1 transition-colors whitespace-nowrap"
          >
            ← 돌아가기
          </button>
          <input
            value={title}
            onChange={e => setTitle(e.target.value)}
            placeholder="보고서 제목 입력"
            className="text-[17px] font-bold bg-bg-0 border border-[var(--bdL)] rounded px-2.5 py-1 outline-none w-[380px] max-w-[480px]"
          />
          <span
            className="px-2.5 py-[3px] text-[10px] font-semibold rounded border whitespace-nowrap"
            style={{ background: 'rgba(251,191,36,0.15)', color: '#f59e0b', borderColor: 'rgba(251,191,36,0.3)' }}
          >
            편집 중
          </span>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setViewMode('all')}
            className="px-3.5 py-1.5 text-[11px] font-semibold rounded cursor-pointer"
            style={{
              border: viewMode === 'all' ? '1px solid var(--cyan)' : '1px solid var(--bd)',
              background: viewMode === 'all' ? 'rgba(6,182,212,0.1)' : 'var(--bg2)',
              color: viewMode === 'all' ? 'var(--cyan)' : 'var(--t3)',
            }}
          >
            전체 보기
          </button>
          <button
            onClick={() => setViewMode('page')}
            className="px-3.5 py-1.5 text-[11px] font-semibold rounded cursor-pointer"
            style={{
              border: viewMode === 'page' ? '1px solid var(--cyan)' : '1px solid var(--bd)',
              background: viewMode === 'page' ? 'rgba(6,182,212,0.1)' : 'var(--bg2)',
              color: viewMode === 'page' ? 'var(--cyan)' : 'var(--t3)',
            }}
          >
            페이지별
          </button>
          <button
            onClick={handleSave}
            className="px-4 py-1.5 text-[11px] font-bold rounded cursor-pointer border border-[#22c55e] bg-[rgba(34,197,94,0.15)] text-status-green"
          >
            저장
          </button>
          <button
            onClick={() => window.print()}
            className="px-3.5 py-1.5 text-[11px] font-semibold rounded cursor-pointer border border-[var(--red)] bg-[rgba(239,68,68,0.1)] text-status-red"
          >
            인쇄 / PDF
          </button>
        </div>
      </div>

      {/* ── Section Tabs (page mode) ── */}
      {viewMode === 'page' && (
        <div className="flex gap-1 px-5 py-2 border-b border-border bg-bg-1 flex-wrap shrink-0">
          {sections.map((sec, i) => (
            <button
              key={i}
              onClick={() => setCurrentPage(i)}
              className="px-3 py-1.5 text-[11px] font-semibold rounded cursor-pointer"
              style={{
                border: currentPage === i ? '1px solid var(--cyan)' : '1px solid var(--bd)',
                background: currentPage === i ? 'rgba(6,182,212,0.15)' : 'transparent',
                color: currentPage === i ? 'var(--cyan)' : 'var(--t3)',
              }}
            >
              {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-[12px] font-semibold rounded border border-border bg-bg-2 cursor-pointer"
                  style={{ color: currentPage === 0 ? 'var(--t3)' : 'var(--t1)', opacity: currentPage === 0 ? 0.4 : 1 }}
                >
                  이전
                </button>
                <span className="px-4 py-2 text-[12px] text-text-2">
                  {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-[12px] font-semibold rounded cursor-pointer"
                  style={{
                    border: '1px solid var(--cyan)',
                    background: 'rgba(6,182,212,0.1)',
                    color: currentPage === sections.length - 1 ? 'var(--t3)' : 'var(--cyan)',
                    opacity: currentPage === sections.length - 1 ? 0.4 : 1,
                  }}
                >
                  다음
                </button>
              </div>
            </div>
          )}
        </div>
      </div>

    </div>
  );
}
