'use client';

import React, { useCallback, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import { FiFileText, FiPlus, FiArrowRight, FiDownload, FiX } from 'react-icons/fi';
import { EnterpriseLoader } from '../../../../../../components/loader/loader';
import {
  getReportContext,
  createReport,
  openReportPdf,
} from '@/lib/api/audit-report-builder.api';
import type { ReportContext, StageType } from '@/lib/api/types/audit-report-builder.types';
import { REPORT_STATUS_CONFIG, STAGE_CONFIG, fmtDate } from '@/lib/api/mappers/audit-report-builder.mappers';
import type { MyAuditRow } from '@/lib/api/types/my-audits.types';

// Self-contained styles for this tab (no dependency on the editor's style file).
const RB_CSS = `
.rb-root { --line:#ece8f4; --muted:#79728f; --text:#211a3a; color:var(--text); font-variant-numeric:tabular-nums; }
.rb-root *, .rb-root *::before, .rb-root *::after { box-sizing:border-box; }
.rb-card { background:#fff; border:1px solid var(--line); border-radius:14px; padding:16px 18px; margin-bottom:14px; }
.rb-card-head { display:flex; align-items:center; justify-content:space-between; gap:10px; margin-bottom:12px; flex-wrap:wrap; }
.rb-card-title { margin:0; font-size:13.5px; font-weight:700; display:flex; align-items:center; gap:8px; }
.rb-card-bar { width:4px; height:16px; border-radius:2px; background:linear-gradient(180deg,#7c3aed,#d4a017); }
.rb-label { font-size:10.5px; font-weight:700; letter-spacing:.08em; text-transform:uppercase; color:var(--muted); }
.rb-select { padding:8px 11px; border:1px solid #d9d3ea; border-radius:9px; background:#fff; font-size:13px; color:var(--text); outline:none; }
.rb-select:focus { border-color:#7c3aed; box-shadow:0 0 0 3px rgba(124,58,237,.12); }
.rb-banner { display:flex; gap:10px; padding:12px 14px; border-radius:12px; margin-bottom:14px; font-size:13px; line-height:1.5; }
.rb-banner-warn { background:#fffbeb; border:1px solid #fcd34d; color:#92400e; }
.rb-btn { display:inline-flex; align-items:center; gap:7px; padding:8px 14px; border-radius:9px; border:1px solid #d9d3ea; background:#fff; color:#3b2f63; font-size:12.5px; font-weight:650; cursor:pointer; white-space:nowrap; transition:transform .15s, box-shadow .15s, opacity .15s; }
.rb-btn:hover:not(:disabled) { transform:translateY(-1px); box-shadow:0 6px 14px -8px rgba(22,10,51,.4); }
.rb-btn:disabled { opacity:.55; cursor:not-allowed; }
.rb-btn-primary { background:linear-gradient(135deg,#7c3aed 0%,#6d28d9 100%); color:#fff; border-color:transparent; }
.rb-btn-sm { padding:5px 10px; font-size:11.5px; border-radius:7px; }
.rb-pill { display:inline-flex; align-items:center; gap:4px; padding:2px 8px; border-radius:99px; font-size:10px; font-weight:600; white-space:nowrap; }
.rb-status { display:inline-flex; align-items:center; gap:6px; padding:4px 11px; border-radius:999px; background:var(--s-bg); color:var(--s-text); font-size:11.5px; font-weight:700; }
.rb-status-dot { width:7px; height:7px; border-radius:50%; background:var(--s-dot); }
.rb-empty { text-align:center; padding:40px 16px; color:#6b7280; font-size:13px; }
.rb-rep-list { display:flex; flex-direction:column; gap:10px; }
.rb-rep-item { display:flex; align-items:center; gap:14px; padding:14px 16px; background:#fff; border:1px solid var(--line); border-radius:14px; flex-wrap:wrap; transition:box-shadow .18s; }
.rb-rep-item:hover { box-shadow:0 10px 24px -18px rgba(22,10,51,.4); }
.rb-rep-main { flex:1; min-width:200px; }
.rb-rep-no { font-family:'JetBrains Mono',ui-monospace,monospace; font-size:12px; font-weight:700; color:#4f46e5; }
.rb-rep-sub { font-size:12px; color:var(--muted); margin-top:3px; }

.rb-picker { display:grid; grid-template-columns:minmax(0,1fr) auto; gap:10px; align-items:end; }
.rb-field { display:flex; flex-direction:column; gap:5px; min-width:0; }
.rb-opt-note { font-size:12px; color:var(--muted); line-height:1.6; margin-top:10px; }
.rb-tag { display:inline-block; padding:2px 8px; border-radius:99px; font-size:10px; font-weight:700; background:#ede9fe; color:#5b21b6; }
.rb-std-row { display:flex; flex-wrap:wrap; gap:6px; align-items:center; margin-top:8px; }
.rb-std-chip { display:inline-flex; align-items:center; gap:6px; padding:4px 10px; border-radius:99px; font-size:12px; font-weight:600; background:#ede9fe; color:#5b21b6; border:1px solid #ddd6fe; }
.rb-std-chip.is-off { background:#f3f4f6; color:#6b7280; border-color:#e5e7eb; text-decoration:line-through; }
.rb-std-chip button { display:inline-flex; align-items:center; border:0; background:transparent; color:inherit; cursor:pointer; padding:0; line-height:1; }
.rb-std-chip button:disabled { cursor:not-allowed; opacity:.4; }
.rb-std-chip .rb-std-restore { text-decoration:none; font-size:11px; font-weight:700; color:#5b21b6; }
.rb-section-title { font-size:10.5px; font-weight:700; letter-spacing:.08em; text-transform:uppercase; color:var(--muted); margin:16px 0 8px; }
@media (max-width:720px){ .rb-picker { grid-template-columns:1fr; } }
`;

type OptKey = string; // "std:<id>" | "combined"

export default function ReportsTab({ row }: { row: MyAuditRow }) {
  const router = useRouter();
  const [ctx, setCtx] = useState<ReportContext | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [creating, setCreating] = useState(false);
  const [stageChoice, setStageChoice] = useState<StageType | ''>('');
  const [choice, setChoice] = useState<OptKey>('');
  // combined report: standards the auditor does NOT want shown on the report (at least two must stay)
  const [excludedStd, setExcludedStd] = useState<number[]>([]);

  const load = useCallback(() => {
    setLoading(true);
    getReportContext(row.id)
      .then((c) => {
        setCtx(c);
        setStageChoice(c.suggested_stage_type ?? '');
        setError(null);
        setChoice((prev) => prev || (c.standards[0] ? `std:${c.standards[0].id}` : ''));
      })
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, [row.id]);

  useEffect(() => {
    load();
  }, [load]);

  const open = (reportId: number) => router.push(`/modules/audits/${row.id}/report/${reportId}`);

  if (loading) return <div style={{ padding: 40, textAlign: 'center' }}><EnterpriseLoader /></div>;

  if (error || !ctx)
    return (
      <div className="rb-root">
        <style>{RB_CSS}</style>
        <div className="rb-banner rb-banner-warn">{error || 'Could not load report info'}</div>
        <button className="rb-btn" onClick={load}>Retry</button>
      </div>
    );

  const standards = ctx.standards.length
    ? ctx.standards
    : (row.standards ?? []).map((s) => ({ id: s.id, name: s.name, title: '' }));
  const canCombine = (ctx.can_combine ?? standards.length > 1) && standards.length > 1;

  // dropdown options: one report per standard + the combined report
  const options = [
    ...standards.map((s) => ({
      key: `std:${s.id}`,
      label: `${s.name}${s.title ? ' — ' + s.title : ''} (separate report)`,
      std: s.id as number | null,
      covers: [s.name],
      report: ctx.reports.find((r) => r.standard_id === s.id),
    })),
    ...(canCombine
      ? [{
          key: 'combined',
          label: `Combined audit report — all ${standards.length} standards`,
          std: null as number | null,
          covers: standards.map((s) => s.name),
          report: ctx.reports.find((r) => r.standard_id === 0),
        }]
      : []),
  ];
  const selected = options.find((o) => o.key === choice) ?? options[0];
  const shownStd = standards.filter((s) => !excludedStd.includes(s.id));
  const canExcludeMore = shownStd.length > 2;
  const excludeStd = (id: number) => { if (id && canExcludeMore) setExcludedStd((p) => (p.includes(id) ? p : [...p, id])); };
  const restoreStd = (id: number) => setExcludedStd((p) => p.filter((x) => x !== id));
  const labelOf = (standardId: number) =>
    standardId === 0 ? 'Combined audit report' : standards.find((s) => s.id === standardId)?.name ?? `Standard ${standardId}`;

  const go = async () => {
    if (!selected) return;
    if (selected.report) return open(selected.report.id);
    if (!stageChoice) return toast.error('Choose the report stage first');
    setCreating(true);
    try {
      const m = await createReport({
        audit_schedule_row_id: row.id,
        ...(selected.std === null ? { combined: true } : { standard_id: selected.std }),
        stage_type: stageChoice,
        ...(selected.std === null && excludedStd.length ? { exclude_standard_ids: excludedStd } : {}),
      });
      toast.success(`Report ${m.report.report_no ?? ''} created`);
      open(m.report.id);
    } catch (e: any) {
      toast.error(e.message || 'Could not create report');
    } finally {
      setCreating(false);
    }
  };

  return (
    <div className="rb-root">
      <style>{RB_CSS}</style>

      <div className="rb-card">
        <div className="rb-card-head">
          <h3 className="rb-card-title"><span className="rb-card-bar" /> Audit Report (Form 04-2a)</h3>
        </div>

        <div className="rb-picker">
          <div className="rb-field">
            <label className="rb-label">1. Audit report</label>
            <select className="rb-select" value={selected?.key ?? ''} onChange={(e) => setChoice(e.target.value)}>
              {options.map((o) => (
                <option key={o.key} value={o.key}>
                  {o.label}{o.report ? ` — ${REPORT_STATUS_CONFIG[o.report.status].label}` : ' — not created'}
                </option>
              ))}
            </select>
          </div>
          <div style={{ display: 'flex', gap: 10, alignItems: 'flex-end', flexWrap: 'wrap' }}>
            {!selected?.report && (
              <div className="rb-field">
                <label className="rb-label">2. Stage</label>
                <select className="rb-select" value={stageChoice} onChange={(e) => setStageChoice(e.target.value as StageType)}>
                  <option value="">— select —</option>
                  {(Object.keys(STAGE_CONFIG) as StageType[]).map((k) => (
                    <option key={k} value={k}>{STAGE_CONFIG[k].label}</option>
                  ))}
                </select>
              </div>
            )}
            <button className="rb-btn rb-btn-primary" onClick={go} disabled={creating || !selected || (!selected.report && !stageChoice)}>
              {selected?.report ? <><FiArrowRight size={13} /> Open report details</> : <><FiPlus size={13} /> {creating ? 'Creating…' : 'Create & open details'}</>}
            </button>
          </div>
        </div>

        {selected && selected.std === null && !selected.report && (
          <div className="rb-field" style={{ marginTop: 12 }}>
            <label className="rb-label">3. Standards shown on the report</label>
            <select
              className="rb-select"
              value=""
              disabled={!canExcludeMore}
              onChange={(e) => excludeStd(Number(e.target.value))}
            >
              <option value="">{canExcludeMore ? '— remove a standard from the report —' : 'At least two standards must stay on a combined report'}</option>
              {shownStd.map((s) => (
                <option key={s.id} value={s.id}>Remove {s.name}{s.title ? ' — ' + s.title : ''}</option>
              ))}
            </select>
            <div className="rb-std-row">
              {standards.map((s) => {
                const off = excludedStd.includes(s.id);
                return (
                  <span key={s.id} className={`rb-std-chip${off ? ' is-off' : ''}`} title={off ? 'Not shown on the report' : 'Shown on the report'}>
                    {s.name}
                    {off ? (
                      <button type="button" className="rb-std-restore" onClick={() => restoreStd(s.id)}>restore</button>
                    ) : (
                      <button type="button" aria-label={`Remove ${s.name} from the report`} disabled={!canExcludeMore} onClick={() => excludeStd(s.id)}><FiX size={12} /></button>
                    )}
                  </span>
                );
              })}
            </div>
          </div>
        )}

        {selected && selected.std === null && selected.report && (
          <p className="rb-opt-note">
            This combined report already exists. To remove a standard from the printed report, open it and use <strong>Details → Standards shown on the report</strong>.
          </p>
        )}

        {selected && (
          <p className="rb-opt-note">
            {selected.std === null ? (
              <>One report that covers <strong>{(excludedStd.length ? shownStd.map((s) => s.name) : selected.covers).join(' · ')}</strong>.{excludedStd.length ? <> Not shown: <strong>{standards.filter((s) => excludedStd.includes(s.id)).map((s) => s.name).join(' · ')}</strong> (can be changed later in the report details).</> : null} The clause list holds every standard, grouped by standard, and the cover and title show all of them.</>
            ) : (
              <>A separate report for <strong>{selected.covers[0]}</strong> only.{canCombine ? ' You can also create the combined report for all standards.' : ''}</>
            )}
            {ctx.suggested_stage_type && !selected.report && (
              <> Suggested stage: <strong>{STAGE_CONFIG[ctx.suggested_stage_type].label}</strong>.</>
            )}
          </p>
        )}
      </div>

      {standards.length === 0 && <div className="rb-empty">No standards are booked for this audit.</div>}

      {ctx.reports.length > 0 && <div className="rb-section-title">Reports for this audit</div>}
      <div className="rb-rep-list">
        {[...ctx.reports].sort((a, b) => (a.standard_id === 0 ? 1 : 0) - (b.standard_id === 0 ? 1 : 0)).map((rep) => {
          const st = REPORT_STATUS_CONFIG[rep.status];
          const sg = STAGE_CONFIG[rep.stage_type];
          return (
            <div className="rb-rep-item" key={rep.id}>
              <span className="rb-pill" style={{ background: sg.bg, color: sg.color }}>{sg.label}</span>
              <div className="rb-rep-main">
                <div className="rb-rep-no">{rep.report_no ?? `#${rep.id}`} · v{rep.version}</div>
                <div className="rb-rep-sub">
                  {rep.standard_id === 0 ? <span className="rb-tag">COMBINED</span> : null} {labelOf(rep.standard_id)}
                  {rep.approved_at ? ` · approved ${fmtDate(rep.approved_at)}` : ''}
                </div>
              </div>
              <span className="rb-status" style={{ ['--s-bg' as any]: st.bg, ['--s-text' as any]: st.text, ['--s-dot' as any]: st.dot }}>
                <span className="rb-status-dot" /> {st.label}
              </span>
              {rep.has_pdf && (rep.status === 'approved' || rep.status === 'locked') && (
                <button className="rb-btn rb-btn-sm" onClick={() => openReportPdf(rep.id).catch((e) => toast.error(e.message))}>
                  <FiDownload size={12} /> PDF
                </button>
              )}
              <button className="rb-btn rb-btn-primary rb-btn-sm" onClick={() => open(rep.id)}>
                <FiArrowRight size={12} /> {rep.status === 'draft' || rep.status === 'returned' ? 'Edit Report' : 'View Report'}
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );
}
