import { useState } from 'react';
import { useForecast, usePipelines } from '../hooks';
import type { ForecastPeriod } from '../types';

const periodLabels: Record<ForecastPeriod, string> = {
  month: 'Monat',
  quarter: 'Quartal',
  year: 'Jahr',
};

function formatCurrency(value: number): string {
  return new Intl.NumberFormat('de-DE', {
    style: 'currency',
    currency: 'EUR',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(value);
}

export function ForecastPage() {
  const [pipelineId, setPipelineId] = useState<string>('');
  const [period, setPeriod] = useState<ForecastPeriod>('quarter');

  const { data: pipelinesData } = usePipelines();
  const { data, isLoading, error } = useForecast(
    pipelineId || undefined,
    period,
  );

  const pipelines = pipelinesData?.data ?? [];
  const forecast = data?.data;

  return (
    <div>
      {/* Header */}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '1.5rem',
        }}
      >
        <h1 style={{ fontSize: '1.5rem', fontWeight: 600 }}>Prognose</h1>
      </div>

      {/* Filter */}
      <div
        style={{
          display: 'flex',
          gap: '1rem',
          marginBottom: '1.5rem',
          alignItems: 'center',
          flexWrap: 'wrap',
        }}
      >
        <div>
          <label
            style={{
              fontSize: '0.8125rem',
              fontWeight: 500,
              color: 'var(--color-text-muted)',
              display: 'block',
              marginBottom: '0.25rem',
            }}
          >
            Pipeline
          </label>
          <select
            value={pipelineId}
            onChange={(e) => setPipelineId(e.target.value)}
            style={{
              padding: '0.5rem 0.75rem',
              border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.875rem',
              background: 'var(--color-bg)',
              color: 'var(--color-text)',
              minWidth: '12rem',
            }}
          >
            <option value="">Alle Pipelines</option>
            {pipelines.map((p) => (
              <option key={p.id} value={p.id}>
                {p.name}
              </option>
            ))}
          </select>
        </div>

        <div>
          <label
            style={{
              fontSize: '0.8125rem',
              fontWeight: 500,
              color: 'var(--color-text-muted)',
              display: 'block',
              marginBottom: '0.25rem',
            }}
          >
            Zeitraum
          </label>
          <div style={{ display: 'flex', gap: '0.25rem' }}>
            {(Object.keys(periodLabels) as ForecastPeriod[]).map((p) => (
              <button
                key={p}
                onClick={() => setPeriod(p)}
                style={{
                  padding: '0.5rem 0.75rem',
                  border: '1px solid var(--color-border)',
                  borderRadius: 'var(--radius-sm)',
                  fontSize: '0.875rem',
                  cursor: 'pointer',
                  background:
                    period === p ? 'var(--color-primary)' : 'var(--color-bg)',
                  color: period === p ? 'white' : 'var(--color-text)',
                  fontWeight: period === p ? 600 : 400,
                }}
              >
                {periodLabels[p]}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Content */}
      {isLoading && <p>Laden...</p>}
      {error && (
        <p style={{ color: 'var(--color-error)' }}>
          Fehler beim Laden der Prognose
        </p>
      )}

      {forecast && (
        <>
          {/* Summary cards */}
          <div
            style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
              gap: '1rem',
              marginBottom: '1.5rem',
            }}
          >
            <SummaryCard
              label="Offene Vorgänge"
              value={String(forecast.totals.dealCount)}
            />
            <SummaryCard
              label="Gesamtwert"
              value={formatCurrency(forecast.totals.totalValue)}
            />
            <SummaryCard
              label="Gewichteter Wert"
              value={formatCurrency(forecast.totals.weightedValue)}
              highlight
            />
            <SummaryCard
              label="Zeitraum"
              value={forecast.period}
            />
          </div>

          {/* Table */}
          <div
            style={{
              background: 'var(--color-bg-card)',
              border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-md)',
              overflow: 'hidden',
            }}
          >
            <table
              style={{
                width: '100%',
                borderCollapse: 'collapse',
                fontSize: '0.875rem',
              }}
            >
              <thead>
                <tr
                  style={{
                    background: 'var(--color-bg)',
                    borderBottom: '1px solid var(--color-border)',
                  }}
                >
                  <th style={thStyle}>Stufe</th>
                  <th style={{ ...thStyle, textAlign: 'right' }}>
                    Wahrscheinlichkeit
                  </th>
                  <th style={{ ...thStyle, textAlign: 'right' }}>Vorgänge</th>
                  <th style={{ ...thStyle, textAlign: 'right' }}>
                    Gesamtwert
                  </th>
                  <th style={{ ...thStyle, textAlign: 'right' }}>
                    Gewichteter Wert
                  </th>
                </tr>
              </thead>
              <tbody>
                {forecast.stages.map((stage) => (
                  <tr
                    key={stage.stageId}
                    style={{
                      borderBottom: '1px solid var(--color-border)',
                    }}
                  >
                    <td style={tdStyle}>{stage.stageName}</td>
                    <td style={{ ...tdStyle, textAlign: 'right' }}>
                      {Math.round(stage.probability * 100)}%
                    </td>
                    <td style={{ ...tdStyle, textAlign: 'right' }}>
                      {stage.dealCount}
                    </td>
                    <td style={{ ...tdStyle, textAlign: 'right' }}>
                      {formatCurrency(stage.totalValue)}
                    </td>
                    <td
                      style={{
                        ...tdStyle,
                        textAlign: 'right',
                        fontWeight: 600,
                      }}
                    >
                      {formatCurrency(stage.weightedValue)}
                    </td>
                  </tr>
                ))}
                {forecast.stages.length === 0 && (
                  <tr>
                    <td
                      colSpan={5}
                      style={{
                        ...tdStyle,
                        textAlign: 'center',
                        color: 'var(--color-text-muted)',
                      }}
                    >
                      Keine offenen Vorgänge in diesem Zeitraum
                    </td>
                  </tr>
                )}
              </tbody>
              {forecast.stages.length > 0 && (
                <tfoot>
                  <tr
                    style={{
                      background: 'var(--color-bg)',
                      fontWeight: 600,
                    }}
                  >
                    <td style={tdStyle}>Gesamt</td>
                    <td style={{ ...tdStyle, textAlign: 'right' }}>&mdash;</td>
                    <td style={{ ...tdStyle, textAlign: 'right' }}>
                      {forecast.totals.dealCount}
                    </td>
                    <td style={{ ...tdStyle, textAlign: 'right' }}>
                      {formatCurrency(forecast.totals.totalValue)}
                    </td>
                    <td style={{ ...tdStyle, textAlign: 'right' }}>
                      {formatCurrency(forecast.totals.weightedValue)}
                    </td>
                  </tr>
                </tfoot>
              )}
            </table>
          </div>
        </>
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Helpers                                                            */
/* ------------------------------------------------------------------ */

const thStyle: React.CSSProperties = {
  padding: '0.75rem 1rem',
  textAlign: 'left',
  fontWeight: 600,
  fontSize: '0.8125rem',
  color: 'var(--color-text-muted)',
};

const tdStyle: React.CSSProperties = {
  padding: '0.75rem 1rem',
  color: 'var(--color-text)',
};

function SummaryCard({
  label,
  value,
  highlight,
}: {
  label: string;
  value: string;
  highlight?: boolean;
}) {
  return (
    <div
      style={{
        background: highlight ? 'var(--color-primary)' : 'var(--color-bg-card)',
        border: highlight ? 'none' : '1px solid var(--color-border)',
        borderRadius: 'var(--radius-md)',
        padding: '1rem 1.25rem',
      }}
    >
      <div
        style={{
          fontSize: '0.8125rem',
          fontWeight: 500,
          color: highlight ? 'rgba(255,255,255,0.8)' : 'var(--color-text-muted)',
          marginBottom: '0.25rem',
        }}
      >
        {label}
      </div>
      <div
        style={{
          fontSize: '1.25rem',
          fontWeight: 700,
          color: highlight ? 'white' : 'var(--color-text)',
        }}
      >
        {value}
      </div>
    </div>
  );
}
