"use client";

import Link from "next/link";
import { useMemo } from "react";
import {
  PageHeader,
  StatCard,
  Panel,
  AdminButton,
  SimpleBars,
  StatusBadge,
} from "@/components/admin/ui";
import { formatCurrency, lowStockThreshold } from "@/components/admin/adminNav";
import { useStore } from "@/context/StoreContext";
import { company } from "@/data/company";

const dayLabels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const monthLabels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"];

export default function AdminDashboardPage() {
  const { store, catalogProducts } = useStore();

  const metrics = useMemo(() => {
    const products = store.products;
    const totalProducts = products.length;
    const lowStock = products.filter((p) => p.stock > 0 && p.stock <= lowStockThreshold).length;
    const outOfStock = products.filter((p) => p.stock <= 0).length;
    const revenue = products.reduce((sum, p) => sum + (p.sale_price || p.selling_price) * Math.max(p.stock, 0), 0);
    const todaySales = Math.round(revenue * 0.018);
    const monthlySales = Math.round(revenue * 0.22);
    const totalOrders = Math.max(products.length * 3, 12);
    const pending = Math.round(totalOrders * 0.12);
    const completed = Math.round(totalOrders * 0.7);
    const cancelled = Math.round(totalOrders * 0.08);
    const returned = Math.round(totalOrders * 0.05);
    const customers = Math.max(48, products.length * 4);
    const newCustomers = Math.max(2, Math.round(customers * 0.03));

    const salesPerDay = dayLabels.map((label, i) => ({
      label,
      value: Math.max(3, Math.round(todaySales * (0.6 + ((i % 5) + 1) * 0.12))),
    }));
    const salesPerMonth = monthLabels.map((label, i) => ({
      label,
      value: Math.max(20, Math.round(monthlySales * (0.5 + i * 0.08))),
    }));

    const bestSellers = [...catalogProducts]
      .sort((a, b) => b.reviews - a.reviews)
      .slice(0, 5)
      .map((p) => ({ label: p.name.slice(0, 12), value: Math.max(1, p.reviews) }));

    const categorySales = store.categories.slice(0, 6).map((category, i) => ({
      label: category.name.slice(0, 10),
      value: Math.max(2, store.products.filter((p) => p.category_id === category.id).length * (4 + i)),
    }));

    const registrations = dayLabels.map((label, i) => ({
      label,
      value: Math.max(1, (i % 4) + 1),
    }));

    return {
      todaySales,
      monthlySales,
      totalOrders,
      pending,
      completed,
      cancelled,
      returned,
      revenue,
      customers,
      newCustomers,
      totalProducts,
      lowStock,
      outOfStock,
      salesPerDay,
      salesPerMonth,
      bestSellers,
      categorySales,
      registrations,
    };
  }, [store, catalogProducts]);

  const recentOrders = [
    { id: "ORD-1042", customer: "Ayesha Khan", total: 89900, status: "Processing" },
    { id: "ORD-1041", customer: "Usman Tariq", total: 125000, status: "Pending" },
    { id: "ORD-1040", customer: "Fatima Noor", total: 45900, status: "Delivered" },
    { id: "ORD-1039", customer: "Ali Raza", total: 28900, status: "Shipped" },
  ];

  const recentCustomers = [
    { name: "Hira Aslam", email: "hira@email.com", joined: "Today" },
    { name: "Bilal Ahmed", email: "bilal@email.com", joined: "Yesterday" },
    { name: "Sana Javed", email: "sana@email.com", joined: "2 days ago" },
  ];

  const recentReviews = store.product_reviews.slice(0, 4);
  const recentPayments = [
    { id: "PAY-882", method: "JazzCash", amount: 89900, status: "Paid" },
    { id: "PAY-881", method: "COD", amount: 125000, status: "Pending" },
    { id: "PAY-880", method: "Bank Transfer", amount: 45900, status: "Paid" },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Dashboard"
        description={`Welcome back to ${company.name} control panel.`}
        actions={
          <>
            <AdminButton href="/admin/products/new">Add Product</AdminButton>
            <AdminButton href="/admin/orders" variant="secondary">View Orders</AdminButton>
          </>
        }
      />

      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <StatCard label="Today's Sales" value={formatCurrency(metrics.todaySales)} tone="success" />
        <StatCard label="Monthly Sales" value={formatCurrency(metrics.monthlySales)} tone="info" />
        <StatCard label="Revenue" value={formatCurrency(metrics.revenue)} />
        <StatCard label="Total Orders" value={metrics.totalOrders} />
        <StatCard label="Pending Orders" value={metrics.pending} tone="warning" />
        <StatCard label="Completed Orders" value={metrics.completed} tone="success" />
        <StatCard label="Cancelled Orders" value={metrics.cancelled} tone="danger" />
        <StatCard label="Returned Orders" value={metrics.returned} tone="warning" />
        <StatCard label="Total Customers" value={metrics.customers} />
        <StatCard label="New Customers Today" value={metrics.newCustomers} tone="info" />
        <StatCard label="Total Products" value={metrics.totalProducts} />
        <StatCard label="Low Stock" value={metrics.lowStock} tone="warning" hint={`≤ ${lowStockThreshold} units`} />
        <StatCard label="Out of Stock" value={metrics.outOfStock} tone="danger" />
      </div>

      <div className="grid gap-4 xl:grid-cols-2">
        <Panel title="Sales per Day" description="Last 7 days">
          <SimpleBars data={metrics.salesPerDay} />
        </Panel>
        <Panel title="Sales per Month" description="Year to date">
          <SimpleBars data={metrics.salesPerMonth} color="hsl(152 60% 42%)" />
        </Panel>
        <Panel title="Best Selling Products">
          {metrics.bestSellers.length ? (
            <SimpleBars data={metrics.bestSellers} color="hsl(262 60% 55%)" />
          ) : (
            <p className="text-sm text-muted-foreground">No product sales data yet.</p>
          )}
        </Panel>
        <Panel title="Category Sales">
          {metrics.categorySales.length ? (
            <SimpleBars data={metrics.categorySales} color="hsl(24 80% 50%)" />
          ) : (
            <p className="text-sm text-muted-foreground">Add categories to see sales mix.</p>
          )}
        </Panel>
        <Panel title="Revenue Graph">
          <SimpleBars data={metrics.salesPerMonth} color="hsl(218 78% 43%)" />
        </Panel>
        <Panel title="Customer Registrations">
          <SimpleBars data={metrics.registrations} color="hsl(190 70% 40%)" />
        </Panel>
      </div>

      <div className="grid gap-4 xl:grid-cols-2">
        <Panel title="New Orders" actions={<AdminButton href="/admin/orders" variant="ghost">View all</AdminButton>}>
          <div className="space-y-3">
            {recentOrders.map((order) => (
              <div key={order.id} className="flex items-center justify-between gap-3 rounded-xl border border-border px-3 py-2.5">
                <div>
                  <p className="text-sm font-semibold">{order.id}</p>
                  <p className="text-xs text-muted-foreground">{order.customer}</p>
                </div>
                <div className="text-right">
                  <p className="text-sm font-semibold">{formatCurrency(order.total)}</p>
                  <StatusBadge status={order.status} />
                </div>
              </div>
            ))}
          </div>
        </Panel>
        <Panel title="Recent Customers" actions={<AdminButton href="/admin/customers" variant="ghost">View all</AdminButton>}>
          <div className="space-y-3">
            {recentCustomers.map((customer) => (
              <div key={customer.email} className="flex items-center justify-between rounded-xl border border-border px-3 py-2.5">
                <div>
                  <p className="text-sm font-semibold">{customer.name}</p>
                  <p className="text-xs text-muted-foreground">{customer.email}</p>
                </div>
                <p className="text-xs text-muted-foreground">{customer.joined}</p>
              </div>
            ))}
          </div>
        </Panel>
        <Panel title="Recent Reviews" actions={<AdminButton href="/admin/reviews" variant="ghost">Moderate</AdminButton>}>
          <div className="space-y-3">
            {recentReviews.length ? recentReviews.map((review) => (
              <div key={review.id} className="rounded-xl border border-border px-3 py-2.5">
                <p className="text-sm font-semibold">Rating {review.rating}/5</p>
                <p className="mt-1 text-xs text-muted-foreground line-clamp-2">{review.review || "No comment"}</p>
              </div>
            )) : (
              <p className="text-sm text-muted-foreground">No reviews loaded yet.</p>
            )}
          </div>
        </Panel>
        <Panel title="Recent Payments" actions={<AdminButton href="/admin/payments" variant="ghost">View all</AdminButton>}>
          <div className="space-y-3">
            {recentPayments.map((payment) => (
              <div key={payment.id} className="flex items-center justify-between rounded-xl border border-border px-3 py-2.5">
                <div>
                  <p className="text-sm font-semibold">{payment.id}</p>
                  <p className="text-xs text-muted-foreground">{payment.method}</p>
                </div>
                <div className="text-right">
                  <p className="text-sm font-semibold">{formatCurrency(payment.amount)}</p>
                  <StatusBadge status={payment.status} />
                </div>
              </div>
            ))}
          </div>
        </Panel>
      </div>

      <Panel title="Quick Actions">
        <div className="flex flex-wrap gap-2">
          <AdminButton href="/admin/products/new">Add Product</AdminButton>
          <AdminButton href="/admin/coupons" variant="secondary">Create Coupon</AdminButton>
          <AdminButton href="/admin/categories" variant="secondary">Create Category</AdminButton>
          <AdminButton href="/admin/brands" variant="secondary">Create Brand</AdminButton>
          <AdminButton href="/admin/orders" variant="secondary">View Orders</AdminButton>
          <AdminButton href="/admin/inventory" variant="secondary">Inventory</AdminButton>
          <AdminButton href="/admin/reports" variant="secondary">Reports</AdminButton>
        </div>
      </Panel>
    </div>
  );
}
