"use client";

import { useAccess } from "@/features/auth/hooks/use-access";
import { Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { PageLoading } from "@/components/page-loading";
import { DashboardDateFilter } from "@/features/dashboard/components/dashboard-date-filter";
import { dashboardOrdersHref, updateQuery, type DashboardPeriod } from "@/lib/dashboard-filters";
import Link from "next/link";
import {
  ShoppingCart,
  Clock,
  Loader2,
  Truck,
  CheckCircle2,
  Building2,
  Package,
  Users,
  Bell,
  Settings,
} from "lucide-react";
import { useDashboard } from "@/features/dashboard/hooks/use-dashboard";
import { OrderStatCard } from "@/features/dashboard/components/order-stat-card";
import { OrdersByCompany } from "@/features/dashboard/components/orders-by-company";
import { OrdersByProduct } from "@/features/dashboard/components/orders-by-product";
import { RecentOrders } from "@/features/dashboard/components/recent-orders";
import { AdminLayout } from "@/components/admin-layout";
import type { SystemRole } from "@/features/manage-users/dtos/manage-users.dto";
import { orderStatusLabel } from "@/lib/order-status";

// ============================================
// Role Display Config
// ============================================

const ROLE_CONFIG: Record<
  SystemRole,
  {
    label: string;
    color: string;
    bgColor: string;
    borderColor: string;
    description: string;
    subtitle: string;
  }
> = {
  super_admin: {
    label: "Super Admin",
    subtitle: "A quick view of the most important admin counts across the Singh Admin Panel.",
    color: "text-purple-600",
    bgColor: "bg-purple-50",
    borderColor: "border-purple-200",
    description: "Full access to all features and settings",
  },
  it_team: {
    label: "IT Team",
    subtitle: "A quick view of key IT management activities and counts.",
    color: "text-blue-600",
    bgColor: "bg-blue-50",
    borderColor: "border-blue-200",
    description: "Access to Dashboard, Companies, Notifications, and Profile",
  },
  delivery_management: {
    label: "Delivery Management",
    subtitle: "A quick view of delivery operations and order status.",
    color: "text-orange-600",
    bgColor: "bg-orange-50",
    borderColor: "border-orange-200",
    description: "Access to Dashboard, Delivery Management, Notifications, and Profile",
  },
  department_user: {
    label: "Community User",
    subtitle: "A quick view of your community's orders and their status.",
    color: "text-emerald-600",
    bgColor: "bg-emerald-50",
    borderColor: "border-emerald-200",
    description: "Access to Dashboard, Orders, Notifications, and Profile",
  },
};

// ============================================
// Dashboard Page Component
// ============================================

export default function DashboardPage() {
  return <Suspense fallback={<PageLoading />}><DashboardContent /></Suspense>;
}

function DashboardContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const startDate = searchParams.get("startDate") ?? "";
  const endDate = searchParams.get("endDate") ?? "";
  const period = (searchParams.get("period") ?? (startDate || endDate ? "custom" : "all")) as DashboardPeriod;
  const {
    data,
    summary,
    ordersByCompany,
    ordersByProduct,
    recentOrders,
    isLoading,
    error,
  } = useDashboard({ startDate: startDate || undefined, endDate: endDate || undefined });

  const { role, canPage } = useAccess();
  const isCommunityUser = role === "department_user";
  const roleConfig = ROLE_CONFIG[role as SystemRole] ?? { subtitle: "A quick view of your permitted activities and counts." };
  const allowedSections = data?.sections ?? [];
  const ordersHref = (status = "") => canPage("/orders") ? dashboardOrdersHref(searchParams.toString(), status) : undefined;

  return (
    <AdminLayout>
      {/* Page Header */}
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-navy-950">
          Dashboard Overview
        </h1>
        <p className="mt-1 text-sm text-gray-500">
          {roleConfig.subtitle}
        </p>
      </div>

      <DashboardDateFilter key={`${period}:${startDate}:${endDate}`} period={period} startDate={startDate} endDate={endDate} onChange={(values) => {
        const query = updateQuery(searchParams.toString(), { ...values, period: values.period === "all" ? "" : values.period });
        router.replace(`/dashboard${query ? `?${query}` : ""}`, { scroll: false });
      }} />

      {/* Error State */}
      {error && (
        <div className="mb-6 rounded-xl border border-red-200 bg-red-50 p-4">
          <p className="text-sm text-red-600">{error}</p>
        </div>
      )}

      {/* Stats Grid — filtered by role */}
      <div className="mb-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
        {allowedSections.includes("orders") && (
          <>
            <OrderStatCard
              title="Total Orders"
              href={ordersHref()}
              value={summary?.totalOrders ?? 0}
              icon={<ShoppingCart className="h-5 w-5" />}
              variant="default"
              isLoading={isLoading}
            />
            <OrderStatCard
              title={isCommunityUser ? "Orders Placed" : `${orderStatusLabel("ordered", role)} Orders`}
              value={summary?.pendingOrders ?? 0}
              href={ordersHref("ordered")}
              icon={<Clock className="h-5 w-5" />}
              variant="warning"
              isLoading={isLoading}
            />
            <OrderStatCard
              title={isCommunityUser ? "Processing" : "Processing Orders"}
              value={summary?.processingOrders ?? 0}
              href={ordersHref("processing")}
              icon={<Loader2 className="h-5 w-5" />}
              variant="info"
              isLoading={isLoading}
            />
            <OrderStatCard
              title={isCommunityUser ? "Shipped" : "Shipped Orders"}
              value={summary?.dispatchedOrders ?? 0}
              href={ordersHref("dispatched")}
              icon={<Truck className="h-5 w-5" />}
              variant="primary"
              isLoading={isLoading}
            />
            <OrderStatCard
              title={isCommunityUser ? "Delivered" : "Delivered Orders"}
              value={summary?.deliveredOrders ?? 0}
              href={ordersHref("delivered")}
              icon={<CheckCircle2 className="h-5 w-5" />}
              variant="success"
              isLoading={isLoading}
            />
          </>
        )}

        {allowedSections.includes("companies") && !allowedSections.includes("orders") && (
          <>
            <OrderStatCard
              title="Total Companies"
              href={canPage("/companies") ? "/companies" : undefined}
              value={summary?.totalCompanies ?? 0}
              icon={<Building2 className="h-5 w-5" />}
              variant="default"
              isLoading={isLoading}
            />
            <OrderStatCard
              title="Active Communities"
              href={canPage("/companies") ? "/companies?view=communities" : undefined}
              value={summary?.activeDepartments ?? 0}
              icon={<Users className="h-5 w-5" />}
              variant="info"
              isLoading={isLoading}
            />
            <OrderStatCard
              title="Community Users"
              href={canPage("/manage-users") ? "/manage-users?context=company" : undefined}
              value={summary?.totalUsers ?? 0}
              icon={<Users className="h-5 w-5" />}
              variant="primary"
              isLoading={isLoading}
            />

          </>
        )}

        {allowedSections.includes("delivery") && !allowedSections.includes("orders") && (
          <>
            <OrderStatCard
              title="To Process (Received)"
              value={summary?.pendingOrders ?? 0}
              href={ordersHref("ordered")}
              icon={<Clock className="h-5 w-5" />}
              variant="warning"
              isLoading={isLoading}
            />
            <OrderStatCard
              title="Processing"
              value={summary?.processingOrders ?? 0}
              href={ordersHref("processing")}
              icon={<Loader2 className="h-5 w-5" />}
              variant="info"
              isLoading={isLoading}
            />
            <OrderStatCard
              title="Shipped"
              value={summary?.dispatchedOrders ?? 0}
              href={ordersHref("dispatched")}
              icon={<Truck className="h-5 w-5" />}
              variant="primary"
              isLoading={isLoading}
            />
            <OrderStatCard
              title="Delivered this month"
              value={summary?.deliveredThisMonth ?? 0}
              href={ordersHref("delivered")}
              icon={<CheckCircle2 className="h-5 w-5" />}
              variant="success"
              isLoading={isLoading}
            />
          </>
        )}
      </div>

      {/* Orders by Company & Orders by Product — only for admin & delivery management */}
      {allowedSections.includes("delivery") && (
        <div className="mb-8 grid gap-6 lg:grid-cols-2">
          <OrdersByCompany
            data={ordersByCompany}
            isLoading={isLoading}
          />
          <OrdersByProduct
            data={ordersByProduct}
            isLoading={isLoading}
          />
        </div>
      )}

      {/* Recent Orders Table — only for roles with order access */}
      {allowedSections.includes("orders") && (
        <RecentOrders orders={recentOrders} isLoading={isLoading} audienceRole={role} />
      )}

      {/* IT Team: Quick Links */}
      {allowedSections.includes("companies") && !allowedSections.includes("orders") && (
        <div className="rounded-xl border border-gray-200/80 bg-white p-6 shadow-sm">
          <h3 className="mb-4 text-base font-semibold text-navy-900">Quick Actions</h3>
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {canPage("/manage-users") && <Link href="/manage-users?context=company" className="flex items-center gap-3 rounded-xl border border-gray-200/80 bg-gray-50/50 p-4 transition-all hover:border-blue-200 hover:bg-blue-50">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-100"><Users className="h-5 w-5 text-blue-600" /></div>
              <div><p className="text-sm font-medium text-gray-900">Manage Users</p><p className="text-xs text-gray-500">View and manage community users</p></div>
            </Link>}
            {canPage("/companies") && <Link
              href="/companies"
              className="flex items-center gap-3 rounded-xl border border-gray-200/80 bg-gray-50/50 p-4 transition-all duration-200 hover:bg-navy-50 hover:border-navy-200 hover:shadow-sm"
            >
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-navy-100">
                <Building2 className="h-5 w-5 text-navy-600" />
              </div>
              <div>
                <p className="text-sm font-medium text-gray-900">Manage Companies</p>
                <p className="text-xs text-gray-500">View and manage companies</p>
              </div>
            </Link>}
            {canPage("/notifications") && <Link
              href="/notifications"
              className="flex items-center gap-3 rounded-xl border border-gray-200/80 bg-gray-50/50 p-4 transition-all duration-200 hover:bg-amber-50 hover:border-amber-200 hover:shadow-sm"
            >
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-amber-100">
                <Bell className="h-5 w-5 text-amber-600" />
              </div>
              <div>
                <p className="text-sm font-medium text-gray-900">Notifications</p>
                <p className="text-xs text-gray-500">View system notifications</p>
              </div>
            </Link>}
            {canPage("/manage-profile") && <Link
              href="/manage-profile"
              className="flex items-center gap-3 rounded-xl border border-gray-200/80 bg-gray-50/50 p-4 transition-all duration-200 hover:bg-emerald-50 hover:border-emerald-200 hover:shadow-sm"
            >
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-emerald-100">
                <Settings className="h-5 w-5 text-emerald-600" />
              </div>
              <div>
                <p className="text-sm font-medium text-gray-900">Manage Profile</p>
                <p className="text-xs text-gray-500">Update your profile</p>
              </div>
            </Link>}
          </div>
        </div>
      )}

      {/* Delivery Management: Quick Links */}
      {allowedSections.includes("delivery") && !allowedSections.includes("orders") && (
        <div className="rounded-xl border border-gray-200/80 bg-white p-6 shadow-sm">
          <h3 className="mb-4 text-base font-semibold text-navy-900">Quick Actions</h3>
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {canPage("/orders") && <Link
              href="/orders"
              className="flex items-center gap-3 rounded-xl border border-gray-200/80 bg-gray-50/50 p-4 transition-all duration-200 hover:bg-orange-50 hover:border-orange-200 hover:shadow-sm"
            >
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-orange-100">
                <Truck className="h-5 w-5 text-orange-600" />
              </div>
              <div>
                <p className="text-sm font-medium text-gray-900">Orders</p>
                <p className="text-xs text-gray-500">Manage deliveries</p>
              </div>
            </Link>}
            {canPage("/notifications") && <Link
              href="/notifications"
              className="flex items-center gap-3 rounded-xl border border-gray-200/80 bg-gray-50/50 p-4 transition-all duration-200 hover:bg-amber-50 hover:border-amber-200 hover:shadow-sm"
            >
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-amber-100">
                <Bell className="h-5 w-5 text-amber-600" />
              </div>
              <div>
                <p className="text-sm font-medium text-gray-900">Notifications</p>
                <p className="text-xs text-gray-500">View delivery alerts</p>
              </div>
            </Link>}
            {canPage("/manage-profile") && <Link
              href="/manage-profile"
              className="flex items-center gap-3 rounded-xl border border-gray-200/80 bg-gray-50/50 p-4 transition-all duration-200 hover:bg-emerald-50 hover:border-emerald-200 hover:shadow-sm"
            >
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-emerald-100">
                <Settings className="h-5 w-5 text-emerald-600" />
              </div>
              <div>
                <p className="text-sm font-medium text-gray-900">Manage Profile</p>
                <p className="text-xs text-gray-500">Update your profile</p>
              </div>
            </Link>}
          </div>
        </div>
      )}
    </AdminLayout>
  );
}
