'use client';

import { useState, useCallback, useRef } from 'react';
import Link from 'next/link';
import { useCurrencyStore } from '@/store/currencyStore';
import {
  TrendingUp,
  TrendingDown,
  ShoppingBag,
  Users,
  DollarSign,
  Package,
  Clock,
  AlertTriangle,
  Star,
  CreditCard,
  Truck,
  Ban,
  RotateCcw,
  Tag,
  Receipt,
  Wallet,
} from 'lucide-react';
import DashboardCharts from './DashboardCharts';
import DashboardDateFilter, {
  type DashboardDateFilterValue,
  resolveDashboardDateRange,
} from './DashboardDateFilter';

// ─── Types ────────────────────────────────────────────────────────────────
interface StatusBreakdownItem {
  status: string;
  count: number;
}

interface PaymentMethodItem {
  method: string;
  count: number;
  revenue: number;
}

interface RecentOrder {
  id: string;
  order_number: string;
  status: string;
  payment_status: string;
  customer_name: string;
  items: number;
  total: number;
  created_at: string;
}

interface TopProduct {
  name: string;
  sku: string;
  sold: number;
  revenue: number;
}

interface TopCustomer {
  name: string;
  email: string;
  orders: number;
  spent: number;
}

interface LowStockItem {
  id: string;
  name: string;
  sku: string;
  stock: number;
  threshold: number;
}

interface DailyTrendItem {
  date: string;
  orders: number;
  revenue: number;
}

interface CategorySale {
  category: string;
  items_sold: number;
  revenue: number;
}

interface HourlyOrderItem {
  hour: number;
  orders: number;
}

interface DashboardData {
  dateRange: { startDate: string | null; endDate: string | null };
  financials: {
    gross_sales: number;
    discounts_given: number;
    net_sales: number;
    tax_collected: number;
    delivery_fees_collected: number;
    total_collected: number;
    refunds_issued: number;
    growth: number | null;
  };
  operational: {
    total_orders: number;
    total_customers: number;
    avg_order_value: number;
  };
  status_breakdown: StatusBreakdownItem[];
  payment_methods: PaymentMethodItem[];
  recent_orders: RecentOrder[];
  top_products: TopProduct[];
  top_customers: TopCustomer[];
  low_stock: LowStockItem[];
  daily_trend: DailyTrendItem[];
  category_sales: CategorySale[];
  hourly_orders: HourlyOrderItem[];
}

interface DashboardContentProps {
  data: DashboardData | null;
}

// ─── Constants ────────────────────────────────────────────────────────────
const STATUS_COLORS: Record<string, string> = {
  pending: '#F59E0B',
  confirmed: '#3B82F6',
  shipped: '#8B5CF6',
  delivered: '#059669',
  cancelled: '#EF4444',
  returned: '#DC2626',
  refunded: '#F97316',
};

const STATUS_ICONS: Record<string, React.ComponentType<{ size?: number; style?: React.CSSProperties }>> = {
  pending: Clock,
  confirmed: Star,
  shipped: Truck,
  delivered: Package,
  cancelled: Ban,
  returned: RotateCcw,
  refunded: DollarSign,
};

const PAYMENT_ICONS: Record<string, React.ComponentType<{ size?: number; style?: React.CSSProperties }>> = {
  cod: DollarSign,
  bank_transfer: CreditCard,
  paypal: CreditCard,
  stripe: CreditCard,
};

const AVATAR_COLORS = ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6'];

const DEFAULT_FILTER: DashboardDateFilterValue = { preset: 'all', customStart: '', customEnd: '' };

// ─── Sub-components ───────────────────────────────────────────────────────
function GrowthIndicator({ growth }: { growth: number | null }) {
  if (growth === null) return <p className="text-xs mt-2 opacity-80">vs previous period: n/a</p>;
  const isPositive = growth >= 0;
  return (
    <div className="flex items-center gap-1 mt-2">
      {isPositive ? <TrendingUp size={14} /> : <TrendingDown size={14} />}
      <span className="text-xs font-medium">{growth}% vs previous period</span>
    </div>
  );
}

function KpiCard({
  label,
  value,
  prefix = '',
  suffix = '',
  gradient,
  icon: Icon,
  footer,
}: {
  label: string;
  value: string | number;
  prefix?: string;
  suffix?: string;
  gradient: string;
  icon: React.ComponentType<{ size?: number }>;
  footer?: React.ReactNode;
}) {
  return (
    <div
      className="p-5 rounded-xl relative overflow-hidden group hover:shadow-lg transition-all"
      style={{ background: gradient, color: 'white' }}
    >
      <div className="absolute top-3 right-3 opacity-20 group-hover:opacity-30 transition-opacity">
        <Icon size={48} />
      </div>
      <p className="text-xs font-medium opacity-80">{label}</p>
      <p className="text-2xl font-bold mt-1">
        {prefix}
        {typeof value === 'number' ? value.toLocaleString() : value}
        {suffix}
      </p>
      {footer || <p className="text-xs mt-2 opacity-80">&nbsp;</p>}
    </div>
  );
}

function SectionHeader({
  title,
  icon: Icon,
  iconBg,
  iconColor,
  linkHref,
  linkText,
}: {
  title: string;
  icon: React.ComponentType<{ size?: number; style?: React.CSSProperties }>;
  iconBg: string;
  iconColor: string;
  linkHref?: string;
  linkText?: string;
}) {
  return (
    <div className="flex items-center justify-between mb-4">
      <div className="flex items-center gap-2">
        <div
          className="w-8 h-8 rounded-lg flex items-center justify-center"
          style={{ background: iconBg }}
        >
          <Icon size={16} style={{ color: iconColor }} />
        </div>
        <h3 className="text-sm font-semibold" style={{ color: 'var(--color-text)' }}>
          {title}
        </h3>
      </div>
      {linkHref && linkText && (
        <Link
          href={linkHref}
          className="text-xs font-medium hover:underline"
          style={{ color: 'var(--color-cta)' }}
        >
          {linkText}
        </Link>
      )}
    </div>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────
export default function DashboardContent({ data: initialData }: DashboardContentProps) {
  const formatAmount = useCurrencyStore((s) => s.formatAmount);
  const [data, setData] = useState(initialData);
  const [filter, setFilter] = useState<DashboardDateFilterValue>(DEFAULT_FILTER);
  const [loading, setLoading] = useState(false);
  const requestId = useRef(0);

  // The Server Component already fetched "All Time" (the default filter)
  // for the first paint — only re-fetch client-side when the admin
  // actually changes the date range, never on mount.
  const handleFilterChange = useCallback((next: DashboardDateFilterValue) => {
    setFilter(next);
    const { startDate, endDate } = resolveDashboardDateRange(next);
    if (next.preset === 'custom' && (!startDate || !endDate)) return; // both custom bounds not picked yet

    const thisRequest = ++requestId.current;
    setLoading(true);
    const params = new URLSearchParams();
    if (startDate && endDate) {
      params.set('startDate', startDate);
      params.set('endDate', endDate);
    }
    fetch(`/api/dashboard/analytics${params.toString() ? `?${params}` : ''}`, { cache: 'no-store' })
      .then((res) => res.json())
      .then((res) => {
        if (thisRequest !== requestId.current) return; // a newer request superseded this one
        if (res.success) setData(res.data);
      })
      .finally(() => {
        if (thisRequest === requestId.current) setLoading(false);
      });
  }, []);

  if (!data) {
    return (
      <div className="text-center py-16">
        <p className="text-lg" style={{ color: 'var(--color-text-secondary)' }}>
          No data available yet. Start by adding products and processing orders!
        </p>
      </div>
    );
  }

  const {
    financials,
    operational,
    status_breakdown,
    payment_methods,
    recent_orders,
    top_products,
    top_customers,
    low_stock,
    daily_trend,
    category_sales,
    hourly_orders,
  } = data;

  return (
    <div className="space-y-6">
      {/* ─── Date Filter ───────────────────────────────────────────── */}
      <div
        className="p-4 rounded-xl"
        style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)' }}
      >
        <DashboardDateFilter value={filter} onChange={handleFilterChange} loading={loading} />
      </div>

      {/* ─── Financial Summary Cards ───────────────────────────────── */}
      <div>
        <h2 className="text-sm font-semibold mb-3" style={{ color: 'var(--color-text-secondary)' }}>
          Financial Summary
        </h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-7 gap-4">
          <KpiCard
            label="Gross Sales"
            value={formatAmount(financials.gross_sales)}
            gradient="linear-gradient(135deg, #64748B, #334155)"
            icon={TrendingUp}
            footer={<p className="text-xs mt-2 opacity-80">Before discounts</p>}
          />
          <KpiCard
            label="Discounts Given"
            value={formatAmount(financials.discounts_given)}
            gradient="linear-gradient(135deg, #F59E0B, #D97706)"
            icon={Tag}
            footer={<p className="text-xs mt-2 opacity-80">Coupons applied</p>}
          />
          <KpiCard
            label="Net Sales"
            value={formatAmount(financials.net_sales)}
            gradient="linear-gradient(135deg, #10B981, #059669)"
            icon={DollarSign}
            footer={<p className="text-xs mt-2 opacity-80">Gross − discounts</p>}
          />
          <KpiCard
            label="Tax Collected"
            value={formatAmount(financials.tax_collected)}
            gradient="linear-gradient(135deg, #8B5CF6, #6D28D9)"
            icon={Receipt}
            footer={<p className="text-xs mt-2 opacity-80">GST / VAT</p>}
          />
          <KpiCard
            label="Delivery Fees"
            value={formatAmount(financials.delivery_fees_collected)}
            gradient="linear-gradient(135deg, #06B6D4, #0891B2)"
            icon={Truck}
            footer={<p className="text-xs mt-2 opacity-80">Shipping collected</p>}
          />
          <KpiCard
            label="Total Collected"
            value={formatAmount(financials.total_collected)}
            gradient="linear-gradient(135deg, #3B82F6, #1D4ED8)"
            icon={Wallet}
            footer={<GrowthIndicator growth={financials.growth} />}
          />
          <KpiCard
            label="Refunds Issued"
            value={formatAmount(financials.refunds_issued)}
            gradient="linear-gradient(135deg, #EF4444, #B91C1C)"
            icon={RotateCcw}
            footer={<p className="text-xs mt-2 opacity-80">Paid back to customers</p>}
          />
        </div>
      </div>

      {/* ─── Operational Cards ─────────────────────────────────────── */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <KpiCard
          label="Total Orders"
          value={operational.total_orders}
          gradient="linear-gradient(135deg, #EC4899, #BE185D)"
          icon={ShoppingBag}
          footer={<p className="text-xs mt-2 opacity-80">In selected period</p>}
        />
        <KpiCard
          label="Total Customers"
          value={operational.total_customers}
          gradient="linear-gradient(135deg, #8B5CF6, #6D28D9)"
          icon={Users}
          footer={<p className="text-xs mt-2 opacity-80">Unique buyers</p>}
        />
        <KpiCard
          label="Avg Order Value"
          value={formatAmount(operational.avg_order_value)}
          gradient="linear-gradient(135deg, #F59E0B, #D97706)"
          icon={Star}
          footer={<p className="text-xs mt-2 opacity-80">Per order</p>}
        />
      </div>

      {/* ─── Sales Charts ──────────────────────────────────────────── */}
      <DashboardCharts
        dailyTrend={daily_trend}
        categorySales={category_sales}
        hourlyOrders={hourly_orders}
        isAllTime={filter.preset === 'all'}
      />

      {/* ─── Status + Payment Methods ──────────────────────────────── */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Status Breakdown */}
        <div
          className="p-5 rounded-xl"
          style={{
            background: 'var(--color-surface)',
            border: '1px solid var(--color-border)',
          }}
        >
          <SectionHeader
            title="Order Status"
            icon={Package}
            iconBg="var(--color-warning-light)"
            iconColor="var(--color-warning)"
          />
          <div className="space-y-2">
            {status_breakdown.slice(0, 6).map((s) => {
              const Icon = STATUS_ICONS[s.status] || Package;
              return (
                <div key={s.status} className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Icon size={14} style={{ color: STATUS_COLORS[s.status] || '#6B7280' }} />
                    <span
                      className="text-xs capitalize"
                      style={{ color: 'var(--color-text-secondary)' }}
                    >
                      {s.status.replace(/_/g, ' ')}
                    </span>
                  </div>
                  <span
                    className="text-xs font-bold px-2 py-0.5 rounded-full"
                    style={{
                      background: `${STATUS_COLORS[s.status]}20`,
                      color: STATUS_COLORS[s.status],
                    }}
                  >
                    {s.count}
                  </span>
                </div>
              );
            })}
          </div>
        </div>

        {/* Payment Methods */}
        <div
          className="p-5 rounded-xl"
          style={{
            background: 'var(--color-surface)',
            border: '1px solid var(--color-border)',
          }}
        >
          <SectionHeader
            title="Payment Methods"
            icon={CreditCard}
            iconBg="var(--color-info-light)"
            iconColor="var(--color-info)"
          />
          <div className="space-y-2">
            {payment_methods.map((p) => {
              const Icon = PAYMENT_ICONS[p.method] || CreditCard;
              return (
                <div key={p.method} className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Icon size={14} style={{ color: 'var(--color-text-secondary)' }} />
                    <span
                      className="text-xs capitalize"
                      style={{ color: 'var(--color-text-secondary)' }}
                    >
                      {p.method.replace(/_/g, ' ')}
                    </span>
                  </div>
                  <div className="text-right">
                    <span className="text-xs font-bold" style={{ color: 'var(--color-text)' }}>
                      {p.count}
                    </span>
                    <span className="text-xs ml-2" style={{ color: 'var(--color-success)' }}>
                      {formatAmount(p.revenue)}
                    </span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* ─── Third Row: Top Products + Top Customers ────────────────── */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Top Products */}
        <div
          className="p-5 rounded-xl"
          style={{
            background: 'var(--color-surface)',
            border: '1px solid var(--color-border)',
          }}
        >
          <SectionHeader
            title="Top Products"
            icon={Star}
            iconBg="var(--color-success-light)"
            iconColor="var(--color-success)"
            linkHref="/admin/dashboard/products"
            linkText="View All →"
          />
          <div className="space-y-3">
            {top_products.map((p, i) => (
              <div
                key={p.sku}
                className="flex items-center justify-between p-3 rounded-lg"
                style={{ background: 'var(--color-surface-alt)' }}
              >
                <div className="flex items-center gap-3">
                  <span
                    className="text-lg font-bold"
                    style={{ color: 'var(--color-text-tertiary)' }}
                  >
                    #{i + 1}
                  </span>
                  <div>
                    <p className="text-sm font-medium" style={{ color: 'var(--color-text)' }}>
                      {p.name}
                    </p>
                    <p className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                      SKU: {p.sku}
                    </p>
                  </div>
                </div>
                <div className="text-right">
                  <p className="text-sm font-bold" style={{ color: 'var(--color-text)' }}>
                    {p.sold} sold
                  </p>
                  <p className="text-xs" style={{ color: 'var(--color-success)' }}>
                    {formatAmount(p.revenue)}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Top Customers */}
        <div
          className="p-5 rounded-xl"
          style={{
            background: 'var(--color-surface)',
            border: '1px solid var(--color-border)',
          }}
        >
          <SectionHeader
            title="Top Customers"
            icon={Users}
            iconBg="var(--color-cta-light)"
            iconColor="var(--color-cta)"
            linkHref="/admin/dashboard/customers"
            linkText="View All →"
          />
          <div className="space-y-3">
            {top_customers.map((c, i) => (
              <div
                key={c.email}
                className="flex items-center justify-between p-3 rounded-lg"
                style={{ background: 'var(--color-surface-alt)' }}
              >
                <div className="flex items-center gap-3">
                  <div
                    className="w-8 h-8 rounded-full flex items-center justify-center text-white text-sm font-bold"
                    style={{
                      background: AVATAR_COLORS[i] || '#6B7280',
                    }}
                  >
                    {c.name?.charAt(0)?.toUpperCase() || '?'}
                  </div>
                  <div>
                    <p className="text-sm font-medium" style={{ color: 'var(--color-text)' }}>
                      {c.name}
                    </p>
                    <p className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                      {c.orders} orders
                    </p>
                  </div>
                </div>
                <p className="text-sm font-bold" style={{ color: 'var(--color-success)' }}>
                  {formatAmount(c.spent)}
                </p>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ─── Fourth Row: Low Stock + Recent Orders ──────────────────── */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Low Stock Alert */}
        {low_stock.length > 0 && (
          <div
            className="p-5 rounded-xl"
            style={{
              background: 'var(--color-surface)',
              border: '1px solid var(--color-border)',
            }}
          >
            <SectionHeader
              title="Low Stock Alert ⚠️"
              icon={AlertTriangle}
              iconBg="var(--color-danger-light)"
              iconColor="var(--color-danger)"
            />
            <div className="space-y-2">
              {low_stock.map((item) => (
                <div
                  key={item.id}
                  className="flex items-center justify-between p-2 rounded-lg"
                  style={{ background: 'var(--color-danger-light)' }}
                >
                  <div>
                    <p className="text-sm font-medium" style={{ color: 'var(--color-text)' }}>
                      {item.name}
                    </p>
                    <p className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                      SKU: {item.sku}
                    </p>
                  </div>
                  <span
                    className="text-xs font-bold px-2 py-1 rounded-full"
                    style={{ background: 'var(--color-danger)', color: 'white' }}
                  >
                    {item.stock} left (min: {item.threshold})
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Recent Orders */}
        <div
          className="p-5 rounded-xl"
          style={{
            background: 'var(--color-surface)',
            border: '1px solid var(--color-border)',
          }}
        >
          <SectionHeader
            title="Recent Orders"
            icon={ShoppingBag}
            iconBg="var(--color-info-light)"
            iconColor="var(--color-info)"
            linkHref="/admin/dashboard/orders"
            linkText="View All →"
          />
          <div className="space-y-2">
            {recent_orders.slice(0, 6).map((order) => (
              <div
                key={order.id}
                className="flex items-center justify-between p-2 rounded-lg hover:bg-surface-alt transition-colors"
                style={{ borderBottom: '1px solid var(--color-border)' }}
              >
                <div className="flex items-center gap-3">
                  <span
                    className="text-xs font-mono font-bold"
                    style={{ color: 'var(--color-cta)' }}
                  >
                    {order.order_number}
                  </span>
                  <span className="text-xs" style={{ color: 'var(--color-text-secondary)' }}>
                    {order.customer_name}
                  </span>
                </div>
                <div className="flex items-center gap-3">
                  <span className="text-xs font-medium" style={{ color: 'var(--color-text)' }}>
                    {formatAmount(order.total)}
                  </span>
                  <span
                    className="text-xs px-2 py-0.5 rounded-full capitalize"
                    style={{
                      background: `${STATUS_COLORS[order.status]}20`,
                      color: STATUS_COLORS[order.status],
                    }}
                  >
                    {order.status.replace(/_/g, ' ')}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
