import React from 'react';
import { FinancialsPanelData } from '../../types/financial';
import { StatementTableMinimal, formatMoney, formatNumber } from '../ui/StatementTableMinimal';
import {
  type UnitScale,
  computeAutoUnit,
  scaleWarningNumbers,
  unitLabel,
} from '../ui/UnitScale';
import { InlineMappingEditor } from '../Mappings/InlineMappingEditor';
import type { MappingCellInfo } from '../../hooks/useEarningsMappings';

interface FinancialsPanelProps {
  data: FinancialsPanelData;
}

const SourceAttribution: React.FC<{ status: FinancialsPanelData['sourceStatus'] }> = ({ status }) => {
  return (
    <div className="text-[11px] font-mono text-term-text-muted">
      SEC EDGAR • companyfacts
      {status.degradedReason && (
        <div className="mt-1 text-warning">{status.degradedReason}</div>
      )}
    </div>
  );
};

export const FinancialsPanel: React.FC<FinancialsPanelProps> = ({ data }) => {
  const [mappingEditor, setMappingEditor] = React.useState<{
    cell: MappingCellInfo;
    top: number;
    left: number;
  } | null>(null);
  const [showSuccessToast, setShowSuccessToast] = React.useState(false);
  const toastTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);

  React.useEffect(() => {
    return () => {
      if (toastTimeoutRef.current) {
        clearTimeout(toastTimeoutRef.current);
      }
    };
  }, []);

  React.useEffect(() => {
    setMappingEditor(null);
  }, [data.symbol, data.frequency]);

  const handleOpenMappingEditor = React.useCallback((cell: MappingCellInfo) => {
    setMappingEditor({
      cell,
      top: 200,
      left: 400,
    });
  }, []);

  const handleMappingSuccess = React.useCallback(() => {
    if (toastTimeoutRef.current) {
      clearTimeout(toastTimeoutRef.current);
    }

    setShowSuccessToast(true);
    toastTimeoutRef.current = setTimeout(() => {
      setShowSuccessToast(false);
      toastTimeoutRef.current = null;
    }, 3000);
  }, []);

  const effectiveUnit: UnitScale = computeAutoUnit(
    data.periods.flatMap((p) => [p.totalAssets, p.totalLiabilities, p.totalEquity, p.revenue]),
  );

  return (
    <div className="financials-panel py-4 overflow-auto">
      {/* Header - Minimal */}
      <header className="mb-4">
        <div className="flex items-start justify-between">
          <div>
            <h2 className="text-heading-lg text-term-text">{data.symbol} Financials</h2>
            <p className="mt-1 text-body-xs text-term-text-muted">
              {data.companyName} • {data.frequency}
            </p>
          </div>
          <div className="text-right text-body-xs">
            <div className="text-term-text-muted">CIK {data.cik}</div>
            {data.latestFiling && (
              <div className="mt-1 text-term-text-tertiary">
                {data.latestFiling.form} filed {data.latestFiling.filingDate}
              </div>
            )}
          </div>
        </div>
      </header>

      <section>
        <div className="mb-2 text-[10px] font-mono uppercase tracking-[0.18em] text-term-text-muted">
          Values in {unitLabel(effectiveUnit)}
        </div>
        <StatementTableMinimal
          periods={data.periods}
          enableMappingCustomizer={true}
          onMapField={handleOpenMappingEditor}
          metrics={[
            { key: 'revenue', label: 'Revenue', render: (period) => formatMoney(period.revenue) },
            { key: 'grossProfit', label: 'Gross Profit', render: (period) => formatMoney(period.grossProfit) },
            { key: 'operatingIncome', label: 'Operating Income', render: (period) => formatMoney(period.operatingIncome) },
            { key: 'netIncome', label: 'Net Income', render: (period) => formatMoney(period.netIncome) },
            { key: 'dilutedEps', label: 'Diluted EPS', render: (period) => formatMoney(period.dilutedEps) },
            { key: 'cash', label: 'Cash & Equivalents', mappable: true, render: (period) => formatMoney(period.cashAndEquivalents) },
            { key: 'assets', label: 'Total Assets', mappable: true, render: (period) => formatMoney(period.totalAssets) },
            { key: 'liabilities', label: 'Total Liabilities', mappable: true, render: (period) => formatMoney(period.totalLiabilities) },
            { key: 'equity', label: 'Total Equity', mappable: true, render: (period) => formatMoney(period.totalEquity) },
            { key: 'shares', label: 'Shares Outstanding', mappable: true, render: (period) => formatNumber(period.sharesOutstanding) },
          ]}
        />
      </section>

      {/* Footer - Minimal attribution */}
      <footer className="mt-4 border-t border-term-border-subtle pt-4">
        <SourceAttribution status={data.sourceStatus} />
        {data.mappingWarnings && data.mappingWarnings.length > 0 && (
          <div className="mt-2 rounded border border-warning/30 bg-warning/5 px-3 py-2">
            <div className="mb-1 text-[11px] font-mono font-semibold text-warning">
              Mapping &amp; Calculation Warnings
            </div>
            <ul className="list-inside list-disc text-[11px] font-mono text-term-text-muted">
              {data.mappingWarnings.map((warning, index) => (
                <li key={index}>{scaleWarningNumbers(warning, effectiveUnit)}</li>
              ))}
            </ul>
          </div>
        )}
      </footer>

      {showSuccessToast && (
        <div
          className="fixed bottom-4 right-4 z-50 rounded-md border border-success-border bg-success-bg px-4 py-3 shadow-lg"
          aria-live="polite"
          role="status"
        >
          <div className="flex items-center gap-3">
            <div className="text-success-text">
              <svg
                className="h-5 w-5"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M5 13l4 4L19 7"
                />
              </svg>
            </div>
            <div>
              <p className="text-sm font-medium text-success-text">
                Mapping saved successfully
              </p>
              <p className="mt-1 text-xs text-success-text-muted">
                Financials data is being refreshed...
              </p>
            </div>
          </div>
        </div>
      )}

      {mappingEditor && (
        <>
          <div
            className="fixed inset-0 z-40 bg-black/20"
            onClick={() => setMappingEditor(null)}
            onKeyDown={(event) => {
              if (
                event.key === 'Escape' ||
                event.key === 'Enter' ||
                event.key === ' '
              ) {
                setMappingEditor(null);
              }
            }}
            role="button"
            tabIndex={0}
            aria-label="Close mapping editor"
            style={{ pointerEvents: 'auto' }}
          />
          <InlineMappingEditor
            key={`${mappingEditor.cell.metricKey}-${mappingEditor.cell.metricLabel}`}
            cellInfo={mappingEditor.cell}
            context={{
              symbol: data.symbol,
              frequency: data.frequency,
              earliestPeriod: data.periods[data.periods.length - 1]?.periodEnd,
              latestPeriod: data.periods[0]?.periodEnd,
            }}
            availableConcepts={data.availableConcepts}
            onSuccess={handleMappingSuccess}
            onClose={() => setMappingEditor(null)}
            position={{ top: mappingEditor.top, left: mappingEditor.left }}
          />
        </>
      )}
    </div>
  );
};
