import { useEffect, useState } from 'react';
import { apiFetch } from '@/utils/api';
import {
  ResponsiveContainer,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  Tooltip,
  CartesianGrid,
  Cell,
} from 'recharts';
import { AlertTriangle, Package, Clock } from 'lucide-react';

interface Arrival {
  week: string;
  poCount: number;
  expectedValue: number;
  vendorCount: number;
}

interface PipelineData {
  arrivals: Arrival[];
  overdue: { count: number; value: number };
  summary: { totalOpenPOs: number; totalOnOrderValue: number; vendorCount: number };
}

function formatCurrency(value: number): string {
  if (value >= 1_000_000) return `$${(value / 1_000_000).toFixed(1)}M`;
  if (value >= 1_000) return `$${(value / 1_000).toFixed(1)}k`;
  return `$${Math.round(value)}`;
}

function formatWeek(dateStr: string): string {
  const d = new Date(dateStr);
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}

export default function PipelineCard() {
  const [data, setData] = useState<PipelineData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    apiFetch('/api/purchase-orders/pipeline')
      .then(res => res.ok ? res.json() : Promise.reject('Failed'))
      .then(setData)
      .catch(err => console.error('Pipeline fetch error:', err))
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="rounded-xl border bg-card p-6">
        <h3 className="text-lg font-semibold mb-4">Incoming Pipeline</h3>
        <div className="h-[200px] flex items-center justify-center">
          <div className="animate-pulse text-muted-foreground">Loading pipeline...</div>
        </div>
      </div>
    );
  }

  if (!data) {
    return (
      <div className="rounded-xl border bg-card p-6">
        <h3 className="text-lg font-semibold mb-4">Incoming Pipeline</h3>
        <p className="text-sm text-destructive">Failed to load pipeline data</p>
      </div>
    );
  }

  const now = new Date();
  const currentWeekStart = new Date(now);
  currentWeekStart.setDate(now.getDate() - now.getDay() + 1); // Monday
  const currentWeekStr = currentWeekStart.toISOString().split('T')[0];

  // Split arrivals into overdue vs upcoming
  const chartData = data.arrivals.map(a => ({
    ...a,
    label: formatWeek(a.week),
    isOverdue: new Date(a.week) < new Date(currentWeekStr),
  }));

  return (
    <div className="rounded-xl border bg-card p-6">
      <div className="flex items-center justify-between mb-4">
        <div>
          <h3 className="text-lg font-semibold">Incoming Pipeline</h3>
          <p className="text-xs text-muted-foreground">Expected PO arrivals by week</p>
        </div>
      </div>

      {/* Summary stats row */}
      <div className="grid grid-cols-3 gap-3 mb-4">
        <div className="flex items-center gap-2 rounded-lg border p-2.5">
          <Package className="h-4 w-4 text-blue-500" />
          <div>
            <p className="text-xs text-muted-foreground">Open POs</p>
            <p className="text-sm font-bold">{data.summary.totalOpenPOs}</p>
          </div>
        </div>
        <div className="flex items-center gap-2 rounded-lg border p-2.5">
          <Clock className="h-4 w-4 text-emerald-500" />
          <div>
            <p className="text-xs text-muted-foreground">On Order</p>
            <p className="text-sm font-bold">{formatCurrency(data.summary.totalOnOrderValue)}</p>
          </div>
        </div>
        {data.overdue.count > 0 ? (
          <div className="flex items-center gap-2 rounded-lg border border-red-200 bg-red-50/50 dark:border-red-900/50 dark:bg-red-950/20 p-2.5">
            <AlertTriangle className="h-4 w-4 text-red-500" />
            <div>
              <p className="text-xs text-red-600 dark:text-red-400">Overdue</p>
              <p className="text-sm font-bold text-red-600 dark:text-red-400">
                {data.overdue.count} POs ({formatCurrency(data.overdue.value)})
              </p>
            </div>
          </div>
        ) : (
          <div className="flex items-center gap-2 rounded-lg border p-2.5">
            <AlertTriangle className="h-4 w-4 text-green-500" />
            <div>
              <p className="text-xs text-muted-foreground">Overdue</p>
              <p className="text-sm font-bold text-green-600">None</p>
            </div>
          </div>
        )}
      </div>

      {/* Arrivals chart */}
      {chartData.length === 0 ? (
        <div className="h-[180px] flex items-center justify-center">
          <p className="text-sm text-muted-foreground">No expected arrivals scheduled</p>
        </div>
      ) : (
        <ResponsiveContainer width="100%" height={180}>
          <BarChart data={chartData}>
            <CartesianGrid strokeDasharray="3 3" className="stroke-muted" vertical={false} />
            <XAxis dataKey="label" tick={{ fontSize: 11 }} />
            <YAxis tickFormatter={formatCurrency} tick={{ fontSize: 11 }} width={55} />
            <Tooltip
              content={({ active, payload }) => {
                if (!active || !payload?.length) return null;
                const d = payload[0].payload as Arrival & { isOverdue: boolean };
                return (
                  <div className="rounded-lg border bg-background p-3 shadow-md text-sm">
                    <p className="font-medium mb-1">
                      Week of {formatWeek(d.week)}
                      {d.isOverdue && <span className="text-red-500 ml-1">(overdue)</span>}
                    </p>
                    <p>{d.poCount} purchase orders</p>
                    <p>Expected value: {formatCurrency(d.expectedValue)}</p>
                    <p>{d.vendorCount} vendors</p>
                  </div>
                );
              }}
            />
            <Bar dataKey="expectedValue" name="Expected Value" radius={[4, 4, 0, 0]}>
              {chartData.map((entry, i) => (
                <Cell
                  key={i}
                  fill={entry.isOverdue ? '#ef4444' : '#2563eb'}
                  opacity={0.8}
                />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      )}
    </div>
  );
}
