"use client";

import { useState } from "react";

import {
  AlertCircle,
  BarChart3,
} from "lucide-react";
import { AdminLayout } from "@/components/admin-layout";
import { useMisReporting } from "@/features/mis-reporting/hooks/use-mis-reporting";
import { MisReportSummary } from "@/features/mis-reporting/components/mis-report-summary";
import { MisReportFilters } from "@/features/mis-reporting/components/mis-report-filters";
import { MisReportTable } from "@/features/mis-reporting/components/mis-report-table";
import {
  MisReportByCompany,
  MisReportByProduct,
} from "@/features/mis-reporting/components/mis-report-charts";
import { MonthlyAdminReports } from "@/features/mis-reporting/components/monthly-admin-reports";
import { useAccess } from "@/features/auth/hooks/use-access";

// ============================================
// MIS Reporting Page
// ============================================

export default function MisReportingPage() {
  const { role } = useAccess();
  const [orderId, setOrderId] = useState("");
  const {
    data,
    summary,
    orders,
    ordersByCompany,
    ordersByProduct,
    filters,
    isLoading,
    error,
    setFilters,
    clearFilters,
    clearError,
    refetch,
  } = useMisReporting();

  const matchingOrders = orders.filter((order) => !orderId.trim() || order.orderId.toLowerCase().includes(orderId.trim().toLowerCase()) || order.orderNumber.toLowerCase().includes(orderId.trim().toLowerCase()));

  return (
    <AdminLayout>
      <div className="space-y-6">
        {/* Page Header */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-navy-900 shadow-sm">
              <BarChart3 className="h-5 w-5 text-white" />
            </div>
            <div>
              <h1 className="text-xl font-bold text-navy-900">MIS Reporting</h1>
              <p className="text-sm text-gray-500">
                Comprehensive order analytics and reporting
              </p>
            </div>
          </div>
        </div>

        {/* Error Banner */}
        {error && (
          <div className="flex items-center gap-3 rounded-xl border border-red-200 bg-red-50 px-4 py-3">
            <AlertCircle className="h-5 w-5 flex-shrink-0 text-red-500" />
            <p className="flex-1 text-sm text-red-700">{error}</p>
            <button
              onClick={clearError}
              className="text-xs font-medium text-red-600 hover:text-red-800"
            >
              Dismiss
            </button>
          </div>
        )}

        {/* Summary Cards */}
        {role === "super_admin" && <p className="text-xs text-gray-600">Live order summary and charts exclude imported report rows.</p>}
        <MisReportSummary summary={summary} isLoading={isLoading} />

        <section aria-label="Order Details reports" className="space-y-6">
          {/* Order Details Table */}
          <MisReportTable
            key={JSON.stringify([filters, orderId])}
            orders={matchingOrders}
            showCosts={role === "super_admin"}
            hideCostDetails
            filterControls={
              <MisReportFilters
                options={data?.filterOptions}
                filters={filters}
                onFiltersChange={setFilters}
                onClear={() => { clearFilters(); setOrderId(""); }}
                showReportTypes={role === "super_admin"}
                orderId={orderId}
                onOrderIdChange={setOrderId}
              />
            }
            monthlyTools={role === "super_admin" && <MonthlyAdminReports key={`${filters.month}-${filters.year}`} onImported={refetch} selectedMonth={filters.month} selectedYear={filters.year} />}
            isLoading={isLoading}
            summary={orderId.trim() || matchingOrders.some((order) => order.isImported) || filters.reportType === "monthly_cost" ? null : summary}
            ordersByCompany={orderId.trim() || matchingOrders.some((order) => order.isImported) || filters.reportType === "monthly_cost" ? [] : ordersByCompany}
            ordersByProduct={orderId.trim() || matchingOrders.some((order) => order.isImported) || filters.reportType === "monthly_cost" ? [] : ordersByProduct}
          />
        </section>

        {/* Charts Row */}
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
          <MisReportByCompany data={ordersByCompany} isLoading={isLoading} />
          <MisReportByProduct data={ordersByProduct} isLoading={isLoading} />
        </div>
      </div>
    </AdminLayout>
  );
}
