'use client';

import React, { useState } from 'react';
import toast from 'react-hot-toast';
import { FiSave, FiZap } from 'react-icons/fi';
import { saveSection, aiGenerateSections } from '@/lib/api/audit-report-builder.api';
import type { PanelProps } from './panelTypes';
import RichTextArea from './RichTextArea';
export default function SectionsPanel({ model, canEdit, onDirty }: PanelProps) {
  const [drafts, setDrafts] = useState<Record<string, string>>(() =>
    Object.fromEntries(model.sections.map((s) => [s.key, s.body])),
  );
  const [base, setBase] = useState<Record<string, string>>(() =>
    Object.fromEntries(model.sections.map((s) => [s.key, s.body])),
  );
  const [busy, setBusy] = useState<string | null>(null);

  /** AI drafts the text and saves it; the auditor can edit it right here. */
  const runAi = async (keys?: string[]) => {
    const unsaved = model.sections.some((s) => drafts[s.key] !== base[s.key]);
    if (unsaved && !keys) {
      toast.error('Save your sections first, then run the AI draft.');
      return;
    }
    setBusy(keys ? `ai-${keys[0]}` : 'ai-all');
    try {
      const res = await aiGenerateSections(model.report.id, { keys, overwrite: !!keys });
      if (res.items.length) {
        const upd = (prev: Record<string, string>) => {
          const n = { ...prev };
          res.items.forEach((it) => (n[it.key] = it.body));
          return n;
        };
        setDrafts(upd);
        setBase(upd);
        toast.success(`AI drafted ${res.items.length} section(s). Please review and edit.`);
      } else toast('Nothing to draft (sections already have text).');
    } catch (e: any) {
      toast.error(e.message || 'AI draft failed');
    } finally {
      setBusy(null);
    }
  };

  const AI_KEYS = ['org_brief', 'audit_brief', 'objective', 'criteria', 'effectiveness', 'improvement_comments'];

  const dirtyKeys = () => model.sections.filter((s) => drafts[s.key] !== base[s.key]).map((s) => s.key);

  const change = (key: string, v: string) => {
    setDrafts((p) => ({ ...p, [key]: v }));
    onDirty('sections', true);
  };

  const saveOne = async (key: string) => {
    setBusy(key);
    try {
      await saveSection(model.report.id, key, drafts[key] ?? '');
      setBase((p) => ({ ...p, [key]: drafts[key] ?? '' }));
      const stillDirty = model.sections.some((s) => s.key !== key && drafts[s.key] !== base[s.key]);
      onDirty('sections', stillDirty);
      toast.success('Section saved');
    } catch (e: any) {
      toast.error(e.message || 'Save failed');
    } finally {
      setBusy(null);
    }
  };

  const saveAll = async () => {
    const keys = dirtyKeys();
    if (!keys.length) return toast('Nothing to save');
    setBusy('all');
    try {
      for (const k of keys) await saveSection(model.report.id, k, drafts[k] ?? '');
      setBase({ ...drafts });
      onDirty('sections', false);
      toast.success(`${keys.length} section(s) saved`);
    } catch (e: any) {
      toast.error(e.message || 'Save failed');
    } finally {
      setBusy(null);
    }
  };

  return (
    <div>
      {model.sections.map((s) => {
        const dirty = drafts[s.key] !== base[s.key];
        return (
          <div className="rb-card" key={s.key}>
            <div className="rb-card-head">
              <h3 className="rb-card-title">
                <span className="rb-card-bar" /> {s.label}
                {dirty && <span className="rb-edited">UNSAVED</span>}
              </h3>
              {canEdit && AI_KEYS.includes(s.key) && (
                <button className="rb-btn rb-btn-sm" disabled={busy !== null} onClick={() => runAi([s.key])}>
                  <FiZap size={12} /> {busy === `ai-${s.key}` ? 'Writing…' : 'AI draft'}
                </button>
              )}
              {canEdit && (
                <button className="rb-btn rb-btn-sm" disabled={!dirty || busy !== null} onClick={() => saveOne(s.key)}>
                  <FiSave size={12} /> {busy === s.key ? 'Saving…' : 'Save'}
                </button>
              )}
            </div>
            <RichTextArea
              rows={6}
              disabled={!canEdit}
              value={drafts[s.key] ?? ''}
              onChange={(v) => change(s.key, v)}
            />
            <div className="rb-hint" style={{ marginTop: 4 }}>
              Select text and press B for bold, or • List for bullets. Leave a blank line between paragraphs.
            </div>
          </div>
        );
      })}
      {canEdit && (
        <div className="rb-savebar">
          <button className="rb-btn" onClick={() => runAi()} disabled={busy !== null} title="Drafts every empty narrative section">
            <FiZap size={14} /> {busy === 'ai-all' ? 'AI is writing…' : 'AI draft empty sections'}
          </button>
          <button className="rb-btn rb-btn-primary" onClick={saveAll} disabled={busy !== null || !dirtyKeys().length}>
            <FiSave size={14} /> {busy === 'all' ? 'Saving…' : 'Save All Sections'}
          </button>
        </div>
      )}
    </div>
  );
}
