'use client';

import { useEffect, useState, useCallback } from 'react';
import { PageHeader } from '@bytelyst/dashboard-components';
import { Button } from '@/components/ui/Primitives';
import { useAuth } from '@/lib/auth-context';
import {
  getBudget,
  getBudgetBurndown,
  pauseBudget,
  resumeBudget,
  budgetUsagePct,
  type FleetBudget,
  type CostBurndown,
} from '@/lib/fleet-client';

export default function FleetBudgetPage() {
  const { token } = useAuth();
  const [budget, setBudget] = useState<FleetBudget | null | undefined>(undefined);
  const [burndown, setBurndown] = useState<CostBurndown | null>(null);
  const [acting, setActing] = useState(false);

  const productId =
    typeof window !== 'undefined' ? (localStorage.getItem('tracker_selected_product') ?? '') : '';

  const refresh = useCallback(async () => {
    if (!productId) {
      setBudget(null);
      return;
    }
    try {
      const [b, bd] = await Promise.all([getBudget(productId), getBudgetBurndown(productId, 30)]);
      setBudget(b);
      setBurndown(bd);
    } catch {
      setBudget(null);
    }
  }, [productId]);

  useEffect(() => {
    if (!token) return;
    refresh();
  }, [token, refresh]);

  const handlePause = async () => {
    if (!productId) return;
    setActing(true);
    try {
      const updated = await pauseBudget(productId);
      setBudget(updated);
    } catch {
      /* degrade */
    } finally {
      setActing(false);
    }
  };

  const handleResume = async () => {
    if (!productId) return;
    setActing(true);
    try {
      const updated = await resumeBudget(productId);
      setBudget(updated);
    } catch {
      /* degrade */
    } finally {
      setActing(false);
    }
  };

  if (budget === undefined) {
    return (
      <div className="p-6">
        <PageHeader title="Fleet Budget" />
        <p className="text-muted-foreground mt-4">Loading budget...</p>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      <PageHeader title="Fleet Budget" />

      {!productId && (
        <p className="text-muted-foreground">
          Select a product from the sidebar to view its budget.
        </p>
      )}

      {productId && budget === null && (
        <div className="rounded-lg border p-6 text-center">
          <p className="text-muted-foreground">
            No budget configured for <strong>{productId}</strong>.
          </p>
          <p className="text-sm text-muted-foreground mt-1">
            Use the API (PUT /fleet/budgets/{productId}) to set a ceiling.
          </p>
        </div>
      )}

      {budget && (
        <div className="rounded-lg border p-6 space-y-4 max-w-md">
          <div className="flex items-center justify-between">
            <h2 className="font-semibold">{budget.productId}</h2>
            <span
              className={`rounded-full px-2 py-0.5 text-xs font-medium ${
                budget.status === 'active'
                  ? 'bg-green-500/20 text-green-700 dark:text-green-400'
                  : 'bg-red-500/20 text-red-700 dark:text-red-400'
              }`}
            >
              {budget.status}
            </span>
          </div>

          {/* Spend bar — guards against a missing/zero ceiling (no NaN bar). */}
          {(() => {
            const hasCeiling = Number.isFinite(budget.ceilingUsd) && budget.ceilingUsd > 0;
            const usagePct = budgetUsagePct(budget.spentUsd, budget.ceilingUsd);
            const overCeiling = hasCeiling && budget.spentUsd >= budget.ceilingUsd;
            return (
              <div>
                <div className="flex justify-between text-sm mb-1">
                  <span>Spent</span>
                  <span>
                    ${budget.spentUsd.toFixed(2)} /{' '}
                    {hasCeiling ? `$${budget.ceilingUsd.toFixed(2)}` : 'no ceiling set'}
                  </span>
                </div>
                <div className="w-full bg-muted rounded-full h-2.5" aria-label="Budget usage bar">
                  <div
                    className={`h-2.5 rounded-full ${overCeiling ? 'bg-red-500' : 'bg-blue-500'}`}
                    style={{ width: `${usagePct}%` }}
                  />
                </div>
                {!hasCeiling && (
                  <p className="text-xs text-muted-foreground mt-1">
                    No spend ceiling configured — usage is unbounded.
                  </p>
                )}
              </div>
            );
          })()}

          <div className="text-sm text-muted-foreground">
            <p>Window: {budget.window}</p>
            <p>Last updated: {new Date(budget.updatedAt).toLocaleString()}</p>
          </div>

          {/* Controls */}
          <div className="flex gap-3">
            {budget.status === 'active' ? (
              <Button
                variant="destructive"
                size="sm"
                onClick={handlePause}
                disabled={acting}
                aria-label="Pause budget"
              >
                {acting ? 'Pausing...' : 'Pause'}
              </Button>
            ) : (
              <Button
                variant="primary"
                size="sm"
                onClick={handleResume}
                disabled={acting}
                aria-label="Resume budget"
              >
                {acting ? 'Resuming...' : 'Resume'}
              </Button>
            )}
          </div>
        </div>
      )}

      {/* Cost burndown */}
      {productId && burndown && burndown.days.length > 0 && <BurndownChart burndown={burndown} />}
    </div>
  );
}

function BurndownChart({ burndown }: { burndown: CostBurndown }) {
  const { days, ceilingUsd, totalUsd } = burndown;
  const maxValue = Math.max(
    ceilingUsd ?? 0,
    ...days.map(d => d.cumulativeUsd),
    1 // avoid divide-by-zero
  );
  const ceilingPct = ceilingUsd ? (ceilingUsd / maxValue) * 100 : null;

  return (
    <section className="rounded-lg border p-6 max-w-3xl">
      <div className="flex items-center justify-between mb-1">
        <h2 className="font-semibold">Cost Burndown</h2>
        <span className="text-sm text-muted-foreground">
          ${totalUsd.toFixed(2)} over {days.length} days
        </span>
      </div>
      <p className="text-xs text-muted-foreground mb-4">
        Cumulative spend per day{ceilingUsd ? ' vs. budget ceiling (dashed)' : ''}.
      </p>

      <div className="relative h-40 flex items-end gap-1" aria-label="Cost burndown chart">
        {ceilingPct !== null && (
          <div
            className="absolute left-0 right-0 border-t border-dashed border-red-500/70"
            style={{ bottom: `${ceilingPct}%` }}
            aria-label={`Budget ceiling $${ceilingUsd?.toFixed(2)}`}
          />
        )}
        {days.map(d => {
          const heightPct = (d.cumulativeUsd / maxValue) * 100;
          const overCeiling = ceilingUsd !== null && d.cumulativeUsd >= ceilingUsd;
          return (
            <div key={d.date} className="flex-1 min-w-0 group relative" style={{ height: '100%' }}>
              <div className="absolute bottom-0 left-0 right-0 flex items-end h-full">
                <div
                  className={`w-full rounded-t ${overCeiling ? 'bg-red-500' : 'bg-blue-500'}`}
                  style={{ height: `${Math.max(heightPct, d.cumulativeUsd > 0 ? 2 : 0)}%` }}
                  title={`${d.date}: $${d.cumulativeUsd.toFixed(2)} cumulative ($${d.costUsd.toFixed(2)} that day)`}
                />
              </div>
            </div>
          );
        })}
      </div>
      <div className="flex justify-between text-xs text-muted-foreground mt-2">
        <span>{days[0]?.date}</span>
        <span>{days[days.length - 1]?.date}</span>
      </div>
    </section>
  );
}
