import React, { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
  FaFolderOpen,
  FaTasks,
  FaClock,
  FaSpinner,
  FaPlus,
  FaSync,
  FaShoppingCart,
  FaTruck,
  FaFileInvoiceDollar,
  FaMoneyBillWave,
  FaClipboardList,
  FaFileContract,
  FaBoxOpen,
  FaUsers,
  FaUserFriends,
  FaClone,
  FaTags,
} from 'react-icons/fa';
import projectService from '../services/projectService';
import salesOrderService from '../services/salesOrderService';
import deliveryNoteService from '../services/deliveryNoteService';
import salesInvoiceService from '../services/salesInvoiceService';
import { paymentEntryService } from '../services/paymentEntryService';
import materialRequestService from '../services/materialRequestService';
import purchaseOrderService from '../services/purchaseOrderService';
import purchaseReceiptService from '../services/purchaseReceiptService';
import masterService from '../services/masterService';
interface HubCounts {
  projects: number | null;
  tasks: number | null;
  timesheets: number | null;
  salesOrders: number | null;
  deliveryNotes: number | null;
  salesInvoices: number | null;
  paymentEntries: number | null;
  materialRequests: number | null;
  purchaseOrders: number | null;
  purchaseReceipts: number | null;
  customers: number | null;
  employees: number | null;
  projectTemplates: number | null;
  activityTypes: number | null;
}

const emptyCounts = (): HubCounts => ({
  projects: null,
  tasks: null,
  timesheets: null,
  salesOrders: null,
  deliveryNotes: null,
  salesInvoices: null,
  paymentEntries: null,
  materialRequests: null,
  purchaseOrders: null,
  purchaseReceipts: null,
  customers: null,
  employees: null,
  projectTemplates: null,
  activityTypes: null,
});

/** Card: tinted panel, themed icon */
const ModuleCard: React.FC<{
  label: string;
  sub?: string;
  icon: React.ReactNode;
  iconClassName?: string;
  cardClassName?: string;
  count?: number | null;
  loading?: boolean;
  onClick: () => void;
  onNew?: () => void;
  secondaryNew?: { onClick: () => void; title: string; icon: React.ReactNode };
}> = ({
  label, sub, icon, count, loading, onClick, onNew,
  iconClassName = 'bg-gradient-to-br from-blue-600 to-indigo-700',
  cardClassName = '',
  secondaryNew,
}) => (
  <div
    className={`group rounded-lg border overflow-hidden hover:shadow-md transition-all cursor-pointer shadow-sm h-full min-w-0 flex flex-col ${cardClassName || 'bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700 hover:border-blue-300/80 dark:hover:border-blue-600'}`}
    onClick={onClick}
  >
    <div className="p-2 flex-1 flex flex-col min-h-0">
      <div className="flex items-start justify-between mb-1 gap-1">
        <div className={`w-7 h-7 rounded-md ${iconClassName} flex items-center justify-center text-white shadow-sm shrink-0`}>
          <span className="text-xs">{icon}</span>
        </div>
        {(onNew || secondaryNew) && (
          <div className="flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
            {onNew && (
              <button
                type="button"
                onClick={(e) => {
                  e.stopPropagation();
                  onNew();
                }}
                className="p-1 rounded-md bg-blue-600 text-white border border-blue-600 hover:bg-blue-700 shadow-sm"
                title={`New ${label}`}
              >
                <FaPlus size={9} />
              </button>
            )}
            {secondaryNew && (
              <button
                type="button"
                onClick={(e) => {
                  e.stopPropagation();
                  secondaryNew.onClick();
                }}
                className="p-1 rounded-md border border-violet-200 dark:border-violet-700 bg-violet-50 dark:bg-violet-900/40 text-violet-700 dark:text-violet-200 hover:bg-violet-100 dark:hover:bg-violet-900/60"
                title={secondaryNew.title}
              >
                <span className="text-[10px] flex items-center gap-0.5 font-bold">
                  <FaPlus size={7} />{secondaryNew.icon}
                </span>
              </button>
            )}
          </div>
        )}
      </div>
      <p className="font-semibold text-gray-900 dark:text-white text-xs leading-tight">{label}</p>
      {sub && <p className="text-[10px] text-gray-500 dark:text-gray-400 mt-0.5 leading-snug line-clamp-2">{sub}</p>}
      {count !== undefined && (
        <p className="text-base font-bold text-gray-900 dark:text-white mt-auto pt-1 leading-none tabular-nums">
          {loading && count === null ? <FaSpinner className="animate-spin text-base text-gray-400" /> : (count ?? 0)}
        </p>
      )}
    </div>
  </div>
);

/** Fills available width evenly — avoids empty space when few tiles sit in a half-width column */
const fluidTileGridClass =
  'grid gap-1.5 w-full [grid-template-columns:repeat(auto-fit,minmax(6.75rem,1fr))]';

const SectionCard: React.FC<{
  title: string;
  subtitle?: string;
  icon: React.ReactNode;
  headerClassName?: string;
  bodyClassName?: string;
  className?: string;
  children: React.ReactNode;
}> = ({
  title, subtitle, icon, children,
  headerClassName = 'bg-gradient-to-r from-slate-600 to-slate-800 dark:from-slate-700 dark:to-slate-900',
  bodyClassName = '',
  className = '',
}) => (
  <div
    className={`rounded-lg overflow-hidden shadow-sm border border-gray-200/70 dark:border-gray-700/80 ring-1 ring-black/[0.03] dark:ring-white/[0.06] flex flex-col min-h-0 h-full ${className}`}
  >
    <div className={`flex items-center gap-1.5 px-2.5 py-1.5 text-white shadow-inner shrink-0 ${headerClassName}`}>
      <span className="opacity-95 drop-shadow-sm shrink-0">{icon}</span>
      <div className="min-w-0">
        <h2 className="text-xs font-semibold leading-tight tracking-tight">{title}</h2>
        {subtitle && <p className="text-[9px] text-white/85 leading-snug mt-0.5 line-clamp-2">{subtitle}</p>}
      </div>
    </div>
    <div className={`p-2 flex-1 min-h-0 ${bodyClassName}`}>{children}</div>
  </div>
);

const ProjectModulePage: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [counts, setCounts] = useState<HubCounts>(emptyCounts);
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(async () => {
    setLoading(true);
    setCounts(emptyCounts());

    const settled = await Promise.allSettled([
      projectService.getModuleCounts(),
      salesOrderService.getSalesOrderCount([]),
      deliveryNoteService.getDeliveryNoteCount([]),
      salesInvoiceService.getSalesInvoiceCount({}),
      paymentEntryService.getPaymentEntryCount([]),
      materialRequestService.getMaterialRequestCount([]),
      purchaseOrderService.getPurchaseOrderCount([]),
      purchaseReceiptService.getPurchaseReceiptCount([]),
      masterService.getCustomerCount({}),
      masterService.getEmployeeCount({}),
      projectService.getProjectTemplateCount({}),
      projectService.getActivityTypeCount({}),
    ]);

    const num = (i: number): number => {
      const r = settled[i];
      return r.status === 'fulfilled' ? (r.value as number) : 0;
    };

    const module =
      settled[0].status === 'fulfilled'
        ? (settled[0].value as { projects: number; tasks: number; timesheets: number })
        : { projects: 0, tasks: 0, timesheets: 0 };

    setCounts({
      projects: module.projects,
      tasks: module.tasks,
      timesheets: module.timesheets,
      salesOrders: num(1),
      deliveryNotes: num(2),
      salesInvoices: num(3),
      paymentEntries: num(4),
      materialRequests: num(5),
      purchaseOrders: num(6),
      purchaseReceipts: num(7),
      customers: num(8),
      employees: num(9),
      projectTemplates: num(10),
      activityTypes: num(11),
    });
    setLoading(false);
  }, []);

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

  const flowLoading = loading;

  return (
    <div className="p-3 min-h-screen bg-gray-50 dark:bg-gray-900 max-w-[1920px] mx-auto">
      <div className="flex flex-col gap-2 mb-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-2.5">
          <div className="w-9 h-9 rounded-lg bg-gradient-to-br from-blue-600 to-indigo-700 flex items-center justify-center shadow-md ring-2 ring-white/50 dark:ring-gray-700/50">
            <FaFolderOpen className="text-white text-sm drop-shadow" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-gray-800 dark:text-white">
              {t('projects.moduleTitle', 'Project Management')}
            </h1>
            <p className="text-xs text-gray-600 dark:text-gray-400 mt-0.5">
              {t('projects.hubSubtitle', 'Projects, tasks, timesheets, and linked other documents.')}
            </p>
          </div>
        </div>
        <button
          type="button"
          onClick={refresh}
          className="p-2 text-gray-600 hover:text-blue-700 dark:text-gray-300 dark:hover:text-blue-400 border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 shadow-sm self-start sm:self-center"
          title={t('common.refresh', 'Refresh')}
        >
          <FaSync size={13} className={loading ? 'animate-spin' : ''} />
        </button>
      </div>

      {/* Summary pills */}
      <div className="flex flex-wrap gap-1.5 mb-2">
        <button
          type="button"
          onClick={() => navigate('/projects/list')}
          className="flex items-center gap-2 text-xs font-semibold px-3 py-1.5 rounded-full border border-sky-200 dark:border-sky-700 bg-gradient-to-r from-sky-100 to-blue-100 dark:from-sky-900/40 dark:to-blue-900/30 text-sky-950 dark:text-sky-100 shadow-sm hover:shadow transition-shadow"
        >
          <span className="text-blue-800 dark:text-sky-300 tabular-nums font-bold">
            {loading && counts.projects === null ? '…' : (counts.projects ?? 0)}
          </span>
          Open projects
        </button>
        <button
          type="button"
          onClick={() => navigate('/projects/tasks')}
          className="flex items-center gap-2 text-xs font-semibold px-3 py-1.5 rounded-full border border-indigo-200 dark:border-indigo-700 bg-gradient-to-r from-indigo-50 to-violet-100 dark:from-indigo-900/35 dark:to-violet-900/25 text-gray-800 dark:text-indigo-100 shadow-sm hover:shadow transition-shadow"
        >
          <span className="text-indigo-700 dark:text-indigo-300 tabular-nums font-bold">
            {loading && counts.tasks === null ? '…' : (counts.tasks ?? 0)}
          </span>
          Tasks
        </button>
        <button
          type="button"
          onClick={() => navigate('/projects/timesheets')}
          className="flex items-center gap-2 text-xs font-semibold px-3 py-1.5 rounded-full border border-emerald-200 dark:border-emerald-700 bg-gradient-to-r from-emerald-50 to-teal-100 dark:from-emerald-900/35 dark:to-teal-900/25 text-gray-800 dark:text-emerald-100 shadow-sm hover:shadow transition-shadow"
        >
          <span className="text-emerald-700 dark:text-emerald-300 tabular-nums font-bold">
            {loading && counts.timesheets === null ? '…' : (counts.timesheets ?? 0)}
          </span>
          Timesheets
        </button>
      </div>

      {/* Two columns on lg+: (Masters + Sales) | (Project & task + Buying) — halves screen, less scroll */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-2 lg:gap-3 lg:items-stretch">
        <div className="flex flex-col gap-2 min-w-0">
      <SectionCard
        title="Masters"
        subtitle="Customers, employees, templates, and activity types."
        icon={<FaUsers size={14} />}
        headerClassName="bg-gradient-to-r from-purple-600 to-violet-700 dark:from-purple-700 dark:to-violet-800"
        bodyClassName="bg-white dark:bg-gray-900/40"
      >
        <div className={fluidTileGridClass}>
          <ModuleCard
            label="Customers"
            sub="Customer master"
            icon={<FaUsers className="text-white" />}
            iconClassName="bg-gradient-to-br from-violet-500 to-purple-700"
            cardClassName="bg-gradient-to-b from-white to-violet-50/40 dark:from-gray-800 dark:to-violet-950/20 border-violet-200/50 dark:border-violet-800/50"
            count={counts.customers}
            loading={loading}
            onClick={() => navigate('/customers')}
            onNew={() => navigate('/customers/new')}
          />
          <ModuleCard
            label="Employees"
            sub="Employee master"
            icon={<FaUserFriends className="text-white" />}
            iconClassName="bg-gradient-to-br from-fuchsia-500 to-pink-700"
            cardClassName="bg-gradient-to-b from-white to-fuchsia-50/35 dark:from-gray-800 dark:to-fuchsia-950/15 border-fuchsia-200/50 dark:border-fuchsia-800/50"
            count={counts.employees}
            loading={loading}
            onClick={() => navigate('/employees')}
            onNew={() => navigate('/employees/new')}
          />
          <ModuleCard
            label="Project template"
            sub="Reusable project templates"
            icon={<FaClone className="text-white" />}
            iconClassName="bg-gradient-to-br from-purple-600 to-indigo-800"
            cardClassName="bg-gradient-to-b from-white to-purple-50/35 dark:from-gray-800 dark:to-purple-950/20 border-purple-200/50 dark:border-purple-800/50"
            count={counts.projectTemplates}
            loading={loading}
            onClick={() => navigate('/projects/templates')}
            onNew={() => navigate('/projects/templates/new')}
          />
          <ModuleCard
            label="Activity type"
            sub="Billing categories"
            icon={<FaTags className="text-white" />}
            iconClassName="bg-gradient-to-br from-cyan-500 to-blue-700"
            cardClassName="bg-gradient-to-b from-white to-cyan-50/30 dark:from-gray-800 dark:to-cyan-950/15 border-cyan-200/50 dark:border-cyan-800/50"
            count={counts.activityTypes}
            loading={loading}
            onClick={() => navigate('/projects/activity-types')}
            onNew={() => navigate('/projects/activity-types/new')}
          />
        </div>
      </SectionCard>

      <SectionCard
        title="Sales flow"
        subtitle="Sales Order -> Delivery Note -> Sales Invoice -> Payment"
        icon={<FaShoppingCart size={14} />}
        headerClassName="bg-gradient-to-r from-green-600 to-emerald-700 dark:from-green-700 dark:to-emerald-800"
        bodyClassName="bg-white dark:bg-gray-900/40"
      >
        <div className={fluidTileGridClass}>
          <ModuleCard
            label="Sales Order"
            sub="Sales flow"
            icon={<FaShoppingCart className="text-white" />}
            iconClassName="bg-gradient-to-br from-emerald-600 to-teal-700"
            cardClassName="bg-gradient-to-b from-white to-emerald-50/45 dark:from-gray-800 dark:to-emerald-950/20 border-emerald-200/55 dark:border-emerald-800/50"
            count={counts.salesOrders}
            loading={flowLoading}
            onClick={() => navigate('/sales-orders')}
          />
          <ModuleCard
            label="Delivery Note"
            sub="Sales flow"
            icon={<FaTruck className="text-white" />}
            iconClassName="bg-gradient-to-br from-cyan-600 to-blue-700"
            cardClassName="bg-gradient-to-b from-white to-cyan-50/40 dark:from-gray-800 dark:to-cyan-950/15 border-cyan-200/55 dark:border-cyan-800/50"
            count={counts.deliveryNotes}
            loading={flowLoading}
            onClick={() => navigate('/delivery-notes')}
          />
          <ModuleCard
            label="Sales Invoice"
            sub="Sales flow"
            icon={<FaFileInvoiceDollar className="text-white" />}
            iconClassName="bg-gradient-to-br from-blue-600 to-indigo-700"
            cardClassName="bg-gradient-to-b from-white to-blue-50/40 dark:from-gray-800 dark:to-blue-950/20 border-blue-200/55 dark:border-blue-800/50"
            count={counts.salesInvoices}
            loading={flowLoading}
            onClick={() => navigate('/invoices')}
          />
          <ModuleCard
            label="Payment Entry"
            sub="Sales flow"
            icon={<FaMoneyBillWave className="text-white" />}
            iconClassName="bg-gradient-to-br from-violet-600 to-purple-800"
            cardClassName="bg-gradient-to-b from-white to-violet-50/40 dark:from-gray-800 dark:to-violet-950/20 border-violet-200/55 dark:border-violet-800/50"
            count={counts.paymentEntries}
            loading={flowLoading}
            onClick={() => navigate('/payment-entries')}
          />
        </div>
      </SectionCard>
        </div>

        <div className="flex flex-col gap-2 min-w-0">
      <SectionCard
        title="Project & task management"
        subtitle="Core project monitoring and planning."
        icon={<FaFolderOpen size={14} />}
        headerClassName="bg-gradient-to-r from-blue-600 to-indigo-700 dark:from-blue-700 dark:to-indigo-800"
        bodyClassName="bg-white dark:bg-gray-900/40"
      >
        <div className={fluidTileGridClass}>
          <ModuleCard
            label="Projects"
            sub="Open projects"
            icon={<FaFolderOpen className="text-white" />}
            iconClassName="bg-gradient-to-br from-sky-500 to-blue-700"
            cardClassName="bg-gradient-to-b from-white to-sky-50/50 dark:from-gray-800 dark:to-sky-950/20 border-sky-200/60 dark:border-sky-800/50"
            count={counts.projects}
            loading={loading}
            onClick={() => navigate('/projects/list')}
            onNew={() => navigate('/projects/list/new')}
          />
          <ModuleCard
            label="Tasks"
            sub="All tasks"
            icon={<FaTasks className="text-white" />}
            iconClassName="bg-gradient-to-br from-indigo-500 to-violet-700"
            cardClassName="bg-gradient-to-b from-white to-indigo-50/40 dark:from-gray-800 dark:to-indigo-950/20 border-indigo-200/50 dark:border-indigo-800/50"
            count={counts.tasks}
            loading={loading}
            onClick={() => navigate('/projects/tasks')}
            onNew={() => navigate('/projects/tasks/new')}
          />
          <ModuleCard
            label="Timesheets"
            sub="Time logs"
            icon={<FaClock className="text-white" />}
            iconClassName="bg-gradient-to-br from-emerald-500 to-teal-700"
            cardClassName="bg-gradient-to-b from-white to-emerald-50/40 dark:from-gray-800 dark:to-emerald-950/20 border-emerald-200/50 dark:border-emerald-800/50"
            count={counts.timesheets}
            loading={loading}
            onClick={() => navigate('/projects/timesheets')}
            onNew={() => navigate('/projects/timesheets/new')}
            secondaryNew={{
              title: 'New Sales Order',
              icon: <FaShoppingCart size={10} />,
              onClick: () => navigate('/sales-orders/new'),
            }}
          />
        </div>
      </SectionCard>

      <SectionCard
        title="Buying / material flow"
        subtitle="Material Request -> Purchase Order -> Purchase Receipt"
        icon={<FaBoxOpen size={14} />}
        headerClassName="bg-gradient-to-r from-amber-500 via-orange-500 to-rose-600 dark:from-amber-600 dark:via-orange-600 dark:to-rose-700"
        bodyClassName="bg-white dark:bg-gray-900/40"
      >
        <div className={fluidTileGridClass}>
          <ModuleCard
            label="Material Request"
            sub="Buying flow"
            icon={<FaClipboardList className="text-white" />}
            iconClassName="bg-gradient-to-br from-amber-500 to-orange-600"
            cardClassName="bg-gradient-to-b from-white to-amber-50/45 dark:from-gray-800 dark:to-amber-950/20 border-amber-200/55 dark:border-amber-800/50"
            count={counts.materialRequests}
            loading={flowLoading}
            onClick={() => navigate('/material-requests')}
          />
          <ModuleCard
            label="Purchase Order"
            sub="Buying flow"
            icon={<FaFileContract className="text-white" />}
            iconClassName="bg-gradient-to-br from-orange-600 to-red-700"
            cardClassName="bg-gradient-to-b from-white to-orange-50/40 dark:from-gray-800 dark:to-orange-950/20 border-orange-200/55 dark:border-orange-800/50"
            count={counts.purchaseOrders}
            loading={flowLoading}
            onClick={() => navigate('/purchase-orders')}
          />
          <ModuleCard
            label="Purchase Receipt"
            sub="Buying flow"
            icon={<FaBoxOpen className="text-white" />}
            iconClassName="bg-gradient-to-br from-rose-600 to-pink-700"
            cardClassName="bg-gradient-to-b from-white to-rose-50/40 dark:from-gray-800 dark:to-rose-950/20 border-rose-200/55 dark:border-rose-800/50"
            count={counts.purchaseReceipts}
            loading={flowLoading}
            onClick={() => navigate('/purchase-receipts')}
          />
        </div>
      </SectionCard>
        </div>
      </div>
    </div>
  );
};

export default ProjectModulePage;
