import {
  Bar,
  CartesianGrid,
  Cell,
  ComposedChart,
  Legend,
  Line,
  ReferenceLine,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts'
import { useIsCoarsePointer } from '../../hooks/useMediaQuery'
import type { ChartDayPoint } from '../../types/economics'

type Props = {
  points: ChartDayPoint[]
  hasGreenBonus: boolean
}

const GREEN = '#22c55e'
const RED = '#ef4444'
const BLUE = '#3b82f6'
const AMBER = '#f59e0b'
const SLATE = '#64748b'

function formatDay(iso: string): string {
  const d = new Date(iso + 'T00:00:00')
  return `${d.getDate()}.`
}

type PayloadEntry = {
  name?: string
  value?: number
  color?: string
  dataKey?: string
}

function CustomTooltip({
  active,
  payload,
  label,
  hasGreenBonus,
}: {
  active?: boolean
  payload?: PayloadEntry[]
  label?: string
  hasGreenBonus: boolean
}) {
  if (!active || !payload?.length || !label) return null

  const gridBalance = payload.find((p) => p.dataKey === 'daily_grid_balance_czk')
  const bonus = payload.find((p) => p.dataKey === 'daily_green_bonus_czk')
  const cumBalance = payload.find((p) => p.dataKey === 'cumulative_balance_czk')
  const cumGrid = payload.find((p) => p.dataKey === 'cumulative_grid_balance_czk')
  const importCost = payload.find((p) => p.dataKey === 'daily_import_cost_czk')
  const exportRev = payload.find((p) => p.dataKey === 'daily_export_revenue_czk')

  const gridVal = gridBalance?.value ?? 0
  const bonusVal = bonus?.value ?? 0
  const total = gridVal + bonusVal

  const fmtCzk = (v: number) => `${v >= 0 ? '+' : ''}${v.toFixed(2)} Kč`

  return (
    <div className="rounded-lg border border-slate-700 bg-slate-800 px-3 py-2 text-xs shadow-lg">
      <p className="mb-1 font-medium text-slate-200">{label}</p>
      <p style={{ color: gridVal >= 0 ? GREEN : RED }}>Síť: {fmtCzk(gridVal)}</p>
      {hasGreenBonus && <p style={{ color: AMBER }}>Bonus: {fmtCzk(bonusVal)}</p>}
      <p className="mt-1 border-t border-slate-700 pt-1 font-semibold" style={{ color: total >= 0 ? GREEN : RED }}>
        Celkem: {fmtCzk(total)}
      </p>
      {importCost && (
        <p className="mt-1 text-slate-400">
          Nákup ze sítě: {(importCost.value ?? 0).toFixed(2)} Kč
        </p>
      )}
      {exportRev && (
        <p className="text-slate-400">Prodej do sítě: {(exportRev.value ?? 0).toFixed(2)} Kč</p>
      )}
      {cumBalance && (
        <p className="mt-1 text-slate-400" style={{ color: BLUE }}>
          Kumulativ: {fmtCzk(cumBalance.value ?? 0)}
        </p>
      )}
      {cumGrid && (
        <p className="text-slate-400" style={{ color: SLATE }}>
          Kumulativ síť: {fmtCzk(cumGrid.value ?? 0)}
        </p>
      )}
    </div>
  )
}

export function EconomicsChart({ points, hasGreenBonus }: Props) {
  // Touch zařízení: tooltip na tap (neblokuje scroll), ne hover.
  const isCoarse = useIsCoarsePointer()

  if (points.length === 0) {
    return (
      <div className="flex h-64 items-center justify-center text-sm text-slate-500">
        Žádná data pro tento měsíc
      </div>
    )
  }

  const data = points.map((p) => ({
    ...p,
    label: formatDay(p.day),
  }))

  return (
    // Výška přes CSS breakpointy (mobil 200 px, desktop 280 px) — žádné window.innerWidth v render.
    <div className="h-chart-md w-full lg:h-chart-xl">
      <ResponsiveContainer width="100%" height="100%">
      <ComposedChart data={data} margin={{ top: 8, right: 16, bottom: 4, left: 0 }}>
        <CartesianGrid strokeDasharray="3 3" stroke="#334155" />
        <XAxis dataKey="label" tick={{ fontSize: 11, fill: '#94a3b8' }} />
        <YAxis
          yAxisId="left"
          tick={{ fontSize: 11, fill: '#94a3b8' }}
          label={{
            value: 'Kč/den',
            angle: -90,
            position: 'insideLeft',
            style: { fontSize: 11, fill: '#94a3b8' },
          }}
        />
        <YAxis
          yAxisId="right"
          orientation="right"
          tick={{ fontSize: 11, fill: BLUE }}
          label={{
            value: 'Kumulativ Kč',
            angle: 90,
            position: 'insideRight',
            style: { fontSize: 11, fill: BLUE },
          }}
        />
        <Tooltip
          trigger={isCoarse ? 'click' : 'hover'}
          content={<CustomTooltip hasGreenBonus={hasGreenBonus} />}
        />
        <Legend
          wrapperStyle={{ fontSize: 11 }}
          formatter={(value: string) => {
            const labels: Record<string, string> = {
              daily_grid_balance_czk: 'Bilance síť',
              daily_green_bonus_czk: 'Zelený bonus',
              daily_import_cost_czk: 'Nákup ze sítě',
              daily_export_revenue_czk: 'Prodej do sítě',
              cumulative_balance_czk: 'Kumulativ vč. bonusu',
              cumulative_grid_balance_czk: 'Kumulativ síť',
            }
            return labels[value] ?? value
          }}
        />
        <ReferenceLine yAxisId="left" y={0} stroke="#475569" strokeDasharray="2 2" />

        {/* Stacked bars: bottom = grid balance, top = green bonus */}
        <Bar
          yAxisId="left"
          dataKey="daily_grid_balance_czk"
          stackId="balance"
          maxBarSize={28}
          radius={hasGreenBonus ? undefined : [3, 3, 0, 0]}
        >
          {data.map((entry, idx) => (
            <Cell
              key={idx}
              fill={entry.daily_grid_balance_czk >= 0 ? GREEN : RED}
              fillOpacity={0.7}
            />
          ))}
        </Bar>
        {hasGreenBonus && (
          <Bar
            yAxisId="left"
            dataKey="daily_green_bonus_czk"
            stackId="balance"
            fill={AMBER}
            fillOpacity={0.8}
            maxBarSize={28}
            radius={[3, 3, 0, 0]}
          />
        )}

        {/* Lines: import cost / export revenue */}
        <Line
          yAxisId="left"
          type="monotone"
          dataKey="daily_import_cost_czk"
          stroke={RED}
          strokeWidth={1.5}
          strokeDasharray="4 2"
          dot={false}
        />
        <Line
          yAxisId="left"
          type="monotone"
          dataKey="daily_export_revenue_czk"
          stroke={GREEN}
          strokeWidth={1.5}
          strokeDasharray="4 2"
          dot={false}
        />

        {/* Cumulative lines (right axis) */}
        <Line
          yAxisId="right"
          type="monotone"
          dataKey="cumulative_balance_czk"
          stroke={BLUE}
          strokeWidth={2}
          dot={{ r: 3, fill: BLUE }}
        />
        <Line
          yAxisId="right"
          type="monotone"
          dataKey="cumulative_grid_balance_czk"
          stroke={SLATE}
          strokeWidth={1.5}
          strokeDasharray="5 3"
          dot={false}
        />
        </ComposedChart>
      </ResponsiveContainer>
    </div>
  )
}
