// app/components/admin/orders/StatsCards.tsx
'use client';

import { useMemo } from 'react';
import { DashboardStats } from '@/types/order';

interface StatsCardsProps {
  stats: DashboardStats;
  loading?: boolean;
}

// ─── Icon helpers ─────────────────────────────────────────────────

function IconDollar() {
  return (
    <svg className="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
    </svg>
  );
}

function IconBag() {
  return (
    <svg className="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
    </svg>
  );
}

function IconInbox() {
  return (
    <svg className="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
    </svg>
  );
}

function IconClock({ small }: { small?: boolean }) {
  const cls = small ? 'w-5 h-5' : 'w-7 h-7';
  return (
    <svg className={cls} fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
    </svg>
  );
}

function IconCheck({ small }: { small?: boolean }) {
  const cls = small ? 'w-5 h-5' : 'w-7 h-7';
  return (
    <svg className={cls} fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
    </svg>
  );
}

function IconEye({ small }: { small?: boolean }) {
  const cls = small ? 'w-5 h-5' : 'w-7 h-7';
  return (
    <svg className={cls} fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
    </svg>
  );
}

function IconTick({ small }: { small?: boolean }) {
  const cls = small ? 'w-5 h-5' : 'w-7 h-7';
  return (
    <svg className={cls} fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
    </svg>
  );
}

function IconX({ small }: { small?: boolean }) {
  const cls = small ? 'w-5 h-5' : 'w-7 h-7';
  return (
    <svg className={cls} fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
    </svg>
  );
}

function IconChart() {
  return (
    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
    </svg>
  );
}

function IconReserve() {
  return (
    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
    </svg>
  );
}

// ─── Skeleton loader ──────────────────────────────────────────────────────────

function SkeletonLoader() {
  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {Array.from({ length: 3 }).map((_, i) => (
          <div key={i} className="bg-var-surface rounded-2xl border border-var-border p-6 animate-pulse">
            <div className="h-4 bg-var-surface-hover rounded w-1/3 mb-4" />
            <div className="h-8 bg-var-surface-hover rounded w-1/2 mb-2" />
            <div className="h-3 bg-var-surface-hover rounded w-2/3" />
          </div>
        ))}
      </div>
      <div className="grid grid-cols-2 lg:grid-cols-5 gap-4">
        {Array.from({ length: 5 }).map((_, i) => (
          <div key={i} className="bg-var-surface rounded-xl border border-var-border p-4 animate-pulse">
            <div className="h-4 bg-var-surface-hover rounded w-1/2 mb-2" />
            <div className="h-6 bg-var-surface-hover rounded w-3/4" />
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function StatsCards({ stats, loading = false }: StatsCardsProps) {
  const s = useMemo(
    () => ({
      totalOrders: stats?.totalOrders ?? 0,
      totalRevenue: stats?.totalRevenue ?? 0,
      pendingOrders: stats?.pendingOrders ?? 0,
      confirmedOrders: stats?.confirmedOrders ?? 0,
      pendingReviewOrders: stats?.pendingReviewOrders ?? 0,
      completedOrders: stats?.completedOrders ?? 0,
      cancelledOrders: stats?.cancelledOrders ?? 0,
      confirmedRevenue: stats?.confirmedRevenue ?? 0,
      pendingReviewRevenue: stats?.pendingReviewRevenue ?? 0,
      completedRevenue: stats?.completedRevenue ?? 0,
      cancelledRevenue: stats?.cancelledRevenue ?? 0,
      reserveBalance: stats?.reserveBalance ?? 0,
      monthlyRevenue: stats?.monthlyRevenue ?? 0,
      monthlyCompletedOrders: stats?.monthlyCompletedOrders ?? 0,
      monthlyConfirmedOrders: stats?.monthlyConfirmedOrders ?? 0,
      monthlyPendingReviewOrders: stats?.monthlyPendingReviewOrders ?? 0,
      monthlyReserveBalance: stats?.monthlyReserveBalance ?? 0,
      monthlyTotalPaidOrders: stats?.monthlyTotalPaidOrders ?? 0,
      monthlyTotalRevenue: stats?.monthlyTotalRevenue ?? 0,
    }),
    [stats]
  );

  if (loading) return <SkeletonLoader />;

  return (
    <div className="space-y-6">
      {/* ── Main Stats ── */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <MainCard
          title="Completed Revenue"
          value={`$${s.completedRevenue.toFixed(2)}`}
          subtitle={`${s.completedOrders} orders completed`}
          icon={<IconDollar />}
          variant="success"
        />
        <MainCard
          title="Total Orders"
          value={String(s.totalOrders)}
          subtitle={`${s.completedOrders} completed, ${s.cancelledOrders} cancelled`}
          icon={<IconBag />}
          variant="primary"
        />
        <MainCard
          title="Reserve Balance"
          value={`$${s.reserveBalance.toFixed(2)}`}
          subtitle={`${s.confirmedOrders} confirmed + ${s.pendingReviewOrders} pending review`}
          icon={<IconInbox />}
          variant="warning"
        />
      </div>

      {/* ── Status Breakdown ── */}
      <section>
        <h3 className="text-sm font-semibold text-var-text-muted uppercase tracking-wider mb-4">
          Order Status Breakdown
        </h3>
        <div className="grid grid-cols-2 lg:grid-cols-5 gap-4">
          <StatusCard
            title="Pending"
            value={s.pendingOrders}
            subtitle="Awaiting confirmation"
            note="Not included in revenue"
            icon={<IconClock small />}
            bgColor="bg-var-warning-bg"
            textColor="text-var-warning-text"
          />
          <StatusCard
            title="Confirmed"
            value={s.confirmedOrders}
            subtitle={`$${s.confirmedRevenue.toFixed(2)} reserved`}
            icon={<IconCheck small />}
            bgColor="bg-var-primary-muted"
            textColor="text-var-primary-text"
          />
          <StatusCard
            title="Pending Review"
            value={s.pendingReviewOrders}
            subtitle={`$${s.pendingReviewRevenue.toFixed(2)} reserved`}
            icon={<IconEye small />}
            bgColor="bg-var-info-bg"
            textColor="text-var-info-text"
          />
          <StatusCard
            title="Completed"
            value={s.completedOrders}
            subtitle={`$${s.completedRevenue.toFixed(2)} earned`}
            icon={<IconTick small />}
            bgColor="bg-var-success-bg"
            textColor="text-var-success-text"
          />
          <StatusCard
            title="Cancelled"
            value={s.cancelledOrders}
            subtitle={`$${s.cancelledRevenue.toFixed(2)} refunded`}
            icon={<IconX small />}
            bgColor="bg-var-danger-bg"
            textColor="text-var-danger-text"
          />
        </div>
      </section>

      {/* ── Monthly Performance ── */}
      <section>
        <h3 className="text-sm font-semibold text-var-text-muted uppercase tracking-wider mb-4">
          This Month Performance
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <MonthlyCard
            title="This Month Revenue"
            value={`$${s.monthlyRevenue.toFixed(2)}`}
            subtitle={`${s.monthlyCompletedOrders} orders completed this month`}
            badge={
              s.totalRevenue > 0
                ? `${((s.monthlyRevenue / s.totalRevenue) * 100).toFixed(1)}% of total`
                : ''
            }
            icon={<IconChart />}
            variant="success"
          />
          <MonthlyCard
            title="This Month Reserve"
            value={`$${s.monthlyReserveBalance.toFixed(2)}`}
            subtitle={`${s.monthlyConfirmedOrders} confirmed + ${s.monthlyPendingReviewOrders} pending review`}
            badge={
              s.reserveBalance > 0
                ? `${((s.monthlyReserveBalance / s.reserveBalance) * 100).toFixed(1)}% of total reserve`
                : ''
            }
            icon={<IconReserve />}
            variant="info"
          />
        </div>
      </section>
    </div>
  );
}

// ─── Card sub-components ──────────────────────────────────────────────────────

interface MainCardProps {
  title: string;
  value: string;
  subtitle: string;
  icon: React.ReactNode;
  variant: 'success' | 'primary' | 'warning';
}

function MainCard({ title, value, subtitle, icon, variant }: MainCardProps) {
  const variantClasses = {
    success: {
      bgLight: 'bg-var-success-bg',
      border: 'border-var-success-border',
      iconBg: 'bg-var-success',
      iconText: 'text-white',
      valueText: 'text-var-success-text',
      gradientBg: 'bg-gradient-green',
    },
    primary: {
      bgLight: 'bg-var-primary-muted',
      border: 'border-var-primary',
      iconBg: 'bg-var-primary',
      iconText: 'text-white',
      valueText: 'text-var-primary-text',
      gradientBg: 'bg-var-primary',
    },
    warning: {
      bgLight: 'bg-var-warning-bg',
      border: 'border-var-warning-border',
      iconBg: 'bg-var-warning',
      iconText: 'text-white',
      valueText: 'text-var-warning-text',
      gradientBg: 'bg-gradient-orange',
    },
  };

  const classes = variantClasses[variant];

  return (
    <div
      className={`relative overflow-hidden ${classes.bgLight} rounded-2xl border ${classes.border} p-6 hover:shadow-var-card transition-all duration-300 group`}
    >
      <div
        className={`absolute top-0 right-0 w-32 h-32 ${classes.gradientBg} opacity-10 rounded-bl-full group-hover:opacity-20 transition-opacity duration-300`}
      />
      <div className="relative z-10">
        <div className="flex items-center justify-between mb-4">
          <div className={`p-3 rounded-xl ${classes.iconBg} shadow-var-card`}>
            <div className={classes.iconText}>{icon}</div>
          </div>
          <span className={`text-3xl font-bold ${classes.valueText}`}>{value}</span>
        </div>
        <h3 className="text-lg font-semibold text-var-text mb-1">{title}</h3>
        <p className="text-sm text-var-text-muted">{subtitle}</p>
        <div className="mt-4 flex items-center text-xs text-var-text-muted">
          <svg className="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
          </svg>
          Only paid orders included
        </div>
      </div>
    </div>
  );
}

interface StatusCardProps {
  title: string;
  value: number;
  subtitle: string;
  note?: string;
  icon: React.ReactNode;
  bgColor: string;
  textColor: string;
}

function StatusCard({ title, value, subtitle, note, icon, bgColor, textColor }: StatusCardProps) {
  return (
    <div className={`bg-var-surface rounded-xl border border-var-border p-4 hover:shadow-var-card transition-all duration-200 ${bgColor} bg-opacity-30`}>
      <div className="flex items-center justify-between mb-3">
        <div className={`p-2 rounded-lg ${bgColor}`}>
          <div className={textColor}>{icon}</div>
        </div>
        <span className={`text-2xl font-bold ${textColor}`}>{value}</span>
      </div>
      <h4 className="text-sm font-medium text-var-text mb-1">{title}</h4>
      <p className="text-xs text-var-text-muted">{subtitle}</p>
      {note && <p className="text-xs text-var-text-muted mt-1">{note}</p>}
    </div>
  );
}

interface MonthlyCardProps {
  title: string;
  value: string;
  subtitle: string;
  badge: string;
  icon: React.ReactNode;
  variant: 'success' | 'info';
}

function MonthlyCard({ title, value, subtitle, badge, icon, variant }: MonthlyCardProps) {
  const variantClasses = {
    success: {
      bg: 'bg-var-success-bg',
      text: 'text-var-success-text',
      iconBg: 'bg-var-success-bg',
    },
    info: {
      bg: 'bg-var-info-bg',
      text: 'text-var-info-text',
      iconBg: 'bg-var-info-bg',
    },
  };

  const classes = variantClasses[variant];

  return (
    <div className="bg-linear-to-r from-var-surface-hover to-var-surface rounded-xl border border-var-border p-5 hover:shadow-var-card transition-all duration-200">
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <div className={`p-3 rounded-xl ${classes.iconBg}`}>
            <div className={classes.text}>{icon}</div>
          </div>
          <div>
            <p className="text-sm text-var-text-muted">{title}</p>
            <p className="text-2xl font-bold text-var-text">{value}</p>
            <p className="text-xs text-var-text-muted mt-1">{subtitle}</p>
          </div>
        </div>
        {badge && (
          <div className="text-right">
            <span className={`text-xs ${classes.text} ${classes.bg} px-2 py-1 rounded-full`}>
              {badge}
            </span>
          </div>
        )}
      </div>
    </div>
  );
}