'use client';

import { useState, useEffect, useCallback } from 'react';
import { useApi } from '@/lib/useApi';
import { useRouter } from 'next/navigation';
import { SetPageHeader } from '@/components/layout/SetPageHeader';
import { Card, Button, Icon, Pill } from '@/components/ui';
import { getPriceAnalytics } from '@/services/prices';
import {
  ResponsiveContainer,
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  Cell,
} from 'recharts';

export default function PricesAnalyticsPage() {
  const { householdId, isLoading } = useApi();
  const router = useRouter();
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const loadAnalytics = useCallback(async () => {
    if (!householdId) return;
    setLoading(true);
    try {
      const result = await getPriceAnalytics(householdId);
      setData(result);
    } catch (err: any) {
      setError(err.message || 'Failed to load analytics');
    } finally {
      setLoading(false);
    }
  }, [householdId]);

  useEffect(() => {
    loadAnalytics();
  }, [loadAnalytics]);

  if (isLoading || loading) return <div style={{ padding: 40 }}>Synthesizing financial graphs...</div>;
  if (error || !data) return <div style={{ padding: 40, color: 'var(--danger)' }}>Error: {error}</div>;

  const COLORS = ['var(--brand)', 'var(--success)', 'var(--warning)', '#a855f7', '#ec4899', '#3b82f6'];

  return (
    <>
      <SetPageHeader
        title="Inflation & Spend Metrics"
        subtitle="Interactive real-time visualization of your historical grocery ledger ledger"
      />

      <div style={{ padding: '28px 32px 64px', maxWidth: 1400, margin: '0 auto' }}>
        
        <div style={{ marginBottom: 24 }}>
          <Button variant="ghost" onClick={() => router.push('/shopping-lists')}>
            <Icon name="chevronLeft" style={{ marginRight: 6, width: 16 }} /> Back to Checklists
          </Button>
        </div>

        {/* 1. Immediate Red Alert Banner: Inflation Markup >10% */}
        {data.priceAlerts.length > 0 && (
          <div style={{
            background: 'rgba(239, 68, 68, 0.08)',
            border: '1px solid rgba(239, 68, 68, 0.3)',
            borderRadius: 'var(--r-lg)',
            padding: 20, marginBottom: 32,
            display: 'flex', gap: 16, alignItems: 'flex-start'
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: '50%',
              background: 'var(--danger)', display: 'flex',
              alignItems: 'center', justifyContent: 'center', flexShrink: 0
            }}>
              <Icon name="alert" style={{ width: 20, color: '#fff' }} />
            </div>
            <div style={{ flex: 1 }}>
              <h4 style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink)', marginBottom: 6 }}>Significant Inflation Markers Detected</h4>
              <p style={{ fontSize: 13, color: 'var(--ink-muted)', marginBottom: 16 }}>The following item markups exceeded the baseline 10% deviation thresholds compared to their trailing averages:</p>
              
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 12 }}>
                {data.priceAlerts.map((alert: any, idx: number) => (
                  <div key={idx} style={{ padding: 12, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--ink)' }}>{alert.productName}</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-muted)' }}>At {alert.storeName}</div>
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      <div style={{ color: 'var(--danger)', fontWeight: 700, fontSize: 14 }}>+{alert.changePercent.toFixed(0)}%</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-muted)' }}>${alert.previousPrice} ➔ ${alert.currentPrice}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* 2. Grid Layout for Interactive Charts */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(500px, 1fr))', gap: 28, marginBottom: 32 }}>
          
          {/* Time Series Spend Trend */}
          <Card style={{ padding: 24 }}>
            <h4 style={{ fontSize: 15, fontWeight: 600, marginBottom: 20 }}>Monthly Spending Velocities</h4>
            <div style={{ height: 300 }}>
              {data.spendingOverTime.length === 0 ? (
                <div style={emptyStyle}>No historical spend records found.</div>
              ) : (
                <ResponsiveContainer width="100%" height="100%">
                  <LineChart data={data.spendingOverTime} margin={{ top: 5, right: 10, left: -20, bottom: 5 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
                    <XAxis dataKey="period" stroke="var(--ink-muted)" fontSize={11} tickLine={false} />
                    <YAxis stroke="var(--ink-muted)" fontSize={11} tickLine={false} />
                    <Tooltip contentStyle={tooltipStyle} />
                    <Line type="monotone" dataKey="total" stroke="var(--brand)" strokeWidth={3} activeDot={{ r: 6 }} />
                  </LineChart>
                </ResponsiveContainer>
              )}
            </div>
          </Card>

          {/* Category Distribution */}
          <Card style={{ padding: 24 }}>
            <h4 style={{ fontSize: 15, fontWeight: 600, marginBottom: 20 }}>Spending Distrubution by Category</h4>
            <div style={{ height: 300 }}>
              {data.spendingByCategory.length === 0 ? (
                <div style={emptyStyle}>No categorized allocations recorded yet.</div>
              ) : (
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={data.spendingByCategory} margin={{ top: 5, right: 10, left: -20, bottom: 5 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
                    <XAxis dataKey="category" stroke="var(--ink-muted)" fontSize={11} tickLine={false} />
                    <YAxis stroke="var(--ink-muted)" fontSize={11} tickLine={false} />
                    <Tooltip contentStyle={tooltipStyle} />
                    <Bar dataKey="total" radius={[4, 4, 0, 0]}>
                      {data.spendingByCategory.map((entry: any, index: number) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Bar>
                  </BarChart>
                </ResponsiveContainer>
              )}
            </div>
          </Card>
        </div>

        {/* 3. Average Basket Comparisons (Grid of Stores) */}
        <Card style={{ padding: 24 }}>
          <h4 style={{ fontSize: 15, fontWeight: 600, marginBottom: 20 }}>Average Complete Basket Totals per Store</h4>
          {data.averageBasketByStore.length === 0 ? (
            <div style={emptyStyle}>Create multiple shopping trips to visualize basket trends.</div>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 20 }}>
              {data.averageBasketByStore.sort((a:any, b:any) => a.avgTotal - b.avgTotal).map((store: any, idx: number) => (
                <div key={store.storeId} style={{
                  padding: 20, background: 'var(--bg-elev)',
                  border: idx === 0 ? '1px solid var(--success)' : '1px solid var(--border)',
                  borderRadius: 'var(--r-md)', position: 'relative', overflow: 'hidden'
                }}>
                  <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-muted)', textTransform: 'uppercase', marginBottom: 8 }}>{store.storeName}</div>
                  <div style={{ fontSize: 28, fontWeight: 700, color: idx === 0 ? 'var(--success)' : 'var(--ink)' }}>${store.avgTotal.toFixed(2)}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 4 }}>Based on {store.tripCount} simulated checkouts</div>
                  {idx === 0 && (
                    <div style={{
                      position: 'absolute', top: 0, right: 0,
                      background: 'var(--success)', color: '#fff',
                      fontSize: 9, padding: '4px 8px', borderBottomLeftRadius: 'var(--r-sm)',
                      fontWeight: 700, textTransform: 'uppercase'
                    }}>Best Value</div>
                  )}
                </div>
              ))}
            </div>
          )}
        </Card>

      </div>
    </>
  );
}

const emptyStyle: React.CSSProperties = {
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  height: '100%', color: 'var(--ink-muted)', fontSize: 13, border: '1px dashed var(--border)',
  borderRadius: 'var(--r-md)'
};

const tooltipStyle: React.CSSProperties = {
  background: '#1f2937', border: '1px solid #374151', borderRadius: 8,
  color: '#fff', fontSize: 12,
};
