"use client";

import { useEffect, useState } from "react";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { API_URL } from '@/lib/api';

interface MonthlyCount {
  month: string;
  count: number;
}

interface MonthlyRevenue {
  month: string;
  revenue: number;
}

interface TopPart {
  partCode: string;
  name: string;
  quantityUsed: number;
  revenue: number;
}

interface LowStockPart {
  partCode: string;
  name: string;
  stockQuantity: number;
  reorderLevel: number;
}

interface ExpiringCoverage {
  machineCode: string;
  customerName: string;
  expiryDate: string;
}

interface ReportSummary {
  serviceCallsByStatus: Record<string, number>;
  serviceCallsByPriority: Record<string, number>;
  serviceCallsByMonth: MonthlyCount[];
  revenueByMonth: MonthlyRevenue[];
  totalPartsRevenue: number;
  totalServiceCalls: number;
  totalCustomers: number;
  totalMachines: number;
  totalEmployees: number;
  topPartsUsed: TopPart[];
  lowStockParts: LowStockPart[];
  expiringWarranties: ExpiringCoverage[];
  expiringAmcs: ExpiringCoverage[];
}

export default function ReportsPage() {
  const [data, setData] = useState<ReportSummary | null>(null);

  useEffect(() => {
    fetch(`${API_URL}/api/reports/summary`)
      .then((res) => res.json())
      .then((d) => setData(d))
      .catch((err) => console.error(err));
  }, []);

  if (!data) {
    return (
      <DashboardLayout>
        <p className="text-slate-500">Loading reports...</p>
      </DashboardLayout>
    );
  }

  const maxMonthCount = Math.max(1, ...data.serviceCallsByMonth.map((m) => m.count));
  const maxRevenue = Math.max(1, ...data.revenueByMonth.map((m) => m.revenue));

  return (
    <DashboardLayout>
      <div className="mb-8">
        <h2 className="text-3xl font-bold">Reports &amp; Analytics</h2>
        <p className="mt-1 text-slate-500">
          Service activity, parts revenue, and coverage health at a glance
        </p>
      </div>

      <div className="mb-8 grid grid-cols-4 gap-6">
        <StatCard title="Total Service Calls" value={data.totalServiceCalls} />
        <StatCard title="Total Customers" value={data.totalCustomers} />
        <StatCard title="Total Machines" value={data.totalMachines} />
        <StatCard
          title="Parts Revenue (AED)"
          value={data.totalPartsRevenue.toFixed(2)}
        />
      </div>

      <div className="mb-8 grid grid-cols-2 gap-6">
        <Card title="Service Calls by Status">
          <BreakdownBars
            entries={data.serviceCallsByStatus}
            colorClass="bg-[#1296E8]"
          />
        </Card>

        <Card title="Service Calls by Priority">
          <BreakdownBars
            entries={data.serviceCallsByPriority}
            colorClass="bg-[#EE302B]"
          />
        </Card>
      </div>

      <div className="mb-8 grid grid-cols-2 gap-6">
        <Card title="Service Calls per Month">
          {data.serviceCallsByMonth.length === 0 ? (
            <EmptyState text="No service call history yet." />
          ) : (
            <div className="flex items-end gap-3" style={{ height: 160 }}>
              {data.serviceCallsByMonth.map((m) => (
                <div key={m.month} className="flex flex-1 flex-col items-center gap-2">
                  <div
                    className="w-full rounded-t-lg bg-[#1296E8]"
                    style={{ height: `${(m.count / maxMonthCount) * 120}px` }}
                  />
                  <span className="text-xs text-slate-500">{m.month}</span>
                  <span className="text-xs font-semibold text-slate-700">{m.count}</span>
                </div>
              ))}
            </div>
          )}
        </Card>

        <Card title="Parts Revenue per Month (AED)">
          {data.revenueByMonth.length === 0 ? (
            <EmptyState text="No parts revenue history yet." />
          ) : (
            <div className="flex items-end gap-3" style={{ height: 160 }}>
              {data.revenueByMonth.map((m) => (
                <div key={m.month} className="flex flex-1 flex-col items-center gap-2">
                  <div
                    className="w-full rounded-t-lg bg-[#EE302B]"
                    style={{ height: `${(m.revenue / maxRevenue) * 120}px` }}
                  />
                  <span className="text-xs text-slate-500">{m.month}</span>
                  <span className="text-xs font-semibold text-slate-700">
                    {m.revenue.toFixed(0)}
                  </span>
                </div>
              ))}
            </div>
          )}
        </Card>
      </div>

      <div className="mb-8 grid grid-cols-2 gap-6">
        <Card title="Top Parts Used">
          {data.topPartsUsed.length === 0 ? (
            <EmptyState text="No parts usage recorded yet." />
          ) : (
            <Table
              headers={["Code", "Name", "Qty Used", "Revenue (AED)"]}
              rows={data.topPartsUsed.map((p) => [
                p.partCode,
                p.name,
                String(p.quantityUsed),
                p.revenue.toFixed(2),
              ])}
            />
          )}
        </Card>

        <Card title="Low Stock Parts">
          {data.lowStockParts.length === 0 ? (
            <EmptyState text="All parts are above reorder level." />
          ) : (
            <Table
              headers={["Code", "Name", "Stock", "Reorder Level"]}
              rows={data.lowStockParts.map((p) => [
                p.partCode,
                p.name,
                String(p.stockQuantity),
                String(p.reorderLevel),
              ])}
              highlightRows
            />
          )}
        </Card>
      </div>

      <div className="grid grid-cols-2 gap-6">
        <Card title="Warranties Expiring Within 30 Days">
          {data.expiringWarranties.length === 0 ? (
            <EmptyState text="No warranties expiring soon." />
          ) : (
            <Table
              headers={["Machine", "Customer", "Expiry"]}
              rows={data.expiringWarranties.map((m) => [
                m.machineCode,
                m.customerName,
                m.expiryDate,
              ])}
              highlightRows
            />
          )}
        </Card>

        <Card title="AMCs Expiring Within 30 Days">
          {data.expiringAmcs.length === 0 ? (
            <EmptyState text="No AMCs expiring soon." />
          ) : (
            <Table
              headers={["Machine", "Customer", "Expiry"]}
              rows={data.expiringAmcs.map((m) => [
                m.machineCode,
                m.customerName,
                m.expiryDate,
              ])}
              highlightRows
            />
          )}
        </Card>
      </div>
    </DashboardLayout>
  );
}

function StatCard({ title, value }: { title: string; value: string | number }) {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
      <p className="text-sm font-medium text-slate-500">{title}</p>
      <p className="mt-3 text-3xl font-bold text-slate-900">{value}</p>
    </div>
  );
}

function Card({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
      <h3 className="mb-5 text-lg font-bold">{title}</h3>
      {children}
    </div>
  );
}

function EmptyState({ text }: { text: string }) {
  return (
    <div className="rounded-xl border border-dashed border-slate-300 p-8 text-center text-slate-500">
      {text}
    </div>
  );
}

function BreakdownBars({
  entries,
  colorClass,
}: {
  entries: Record<string, number>;
  colorClass: string;
}) {
  const items = Object.entries(entries);
  const max = Math.max(1, ...items.map(([, count]) => count));

  if (items.length === 0) {
    return <EmptyState text="No data yet." />;
  }

  return (
    <div className="space-y-3">
      {items.map(([label, count]) => (
        <div key={label}>
          <div className="mb-1 flex justify-between text-sm">
            <span className="font-medium text-slate-700">{label}</span>
            <span className="text-slate-500">{count}</span>
          </div>
          <div className="h-2 w-full rounded-full bg-slate-100">
            <div
              className={`h-2 rounded-full ${colorClass}`}
              style={{ width: `${(count / max) * 100}%` }}
            />
          </div>
        </div>
      ))}
    </div>
  );
}

function Table({
  headers,
  rows,
  highlightRows,
}: {
  headers: string[];
  rows: string[][];
  highlightRows?: boolean;
}) {
  return (
    <div className="overflow-hidden rounded-xl border border-slate-200">
      <table className="w-full text-sm">
        <thead className="bg-slate-50">
          <tr>
            {headers.map((h) => (
              <th key={h} className="px-4 py-2 text-left">
                {h}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((row, i) => (
            <tr
              key={i}
              className={`border-t border-slate-100 ${
                highlightRows ? "bg-red-50/40" : ""
              }`}
            >
              {row.map((cell, j) => (
                <td key={j} className="px-4 py-2">
                  {cell}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
