"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { sellerApi } from "@/lib/api/seller";
import { useToken } from "@/lib/auth/useToken";
import type { ApiSellerDashboard } from "@/lib/api/types";
import { ShoppingBag, Wallet, Package, Clock, IndianRupee, Inbox, ArrowRight, PieChart, BellRing, ChevronRight, MapPin } from "lucide-react";
import Loader from "@/components/ui/Loader";
import Countdown from "@/components/rfq/Countdown";
import SellerProductsCard from "./SellerProductsCard";

/**
 * A tile opens the list it counts, as on the buyer dashboard. `flag` marks a
 * tile that needs the seller now (new RFQs with the timer running): red ring,
 * a pulsing dot and a label.
 */
function StatCard({
  label,
  value,
  icon: Icon,
  tone,
  href,
  flag,
}: {
  label: string;
  value: string | number;
  icon: React.ElementType;
  tone: string;
  href?: string;
  flag?: string | null;
}) {
  const body = (
    <>
      <div className="flex items-center justify-between">
        <span className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">{label}</span>
        <span className={`relative flex h-8 w-8 items-center justify-center rounded-lg ${tone}`}>
          <Icon className="h-4 w-4" />
          {flag && (
            <span className="absolute -right-1 -top-1 flex h-3 w-3">
              <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-[#CC1414] opacity-60" />
              <span className="relative inline-flex h-3 w-3 rounded-full bg-[#CC1414] ring-2 ring-white" />
            </span>
          )}
        </span>
      </div>
      <div className="mt-2 flex items-center gap-2">
        <span className="text-xl font-bold text-gray-900">{value}</span>
        {flag && (
          <span className="rounded-full bg-[#CC1414] px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-white">{flag}</span>
        )}
      </div>
    </>
  );
  const className = `rounded-xl p-4 shadow-sm transition ${
    flag ? "bg-red-50/60 ring-2 ring-[#CC1414]/60" : "bg-white ring-1 ring-gray-100"
  } ${href ? "hover:shadow-md hover:ring-[#CC1414]/50" : ""}`;

  return href ? (
    <Link href={href} className={className}>
      {body}
    </Link>
  ) : (
    <div className={className}>{body}</div>
  );
}

function ProgressBar({ label, value, total, tone, href }: { label: string; value: number; total: number; tone: string; href: string }) {
  // A zero shows an empty track; a small non-zero still gets a visible sliver.
  const width = total > 0 && value > 0 ? Math.max(8, Math.round((value / total) * 100)) : 0;

  return (
    <Link href={href} className="group -mx-2 block space-y-1.5 rounded-lg px-2 py-1 transition hover:bg-gray-50">
      <div className="flex items-center justify-between text-sm">
        <span className="font-medium text-gray-700 group-hover:text-[#CC1414]">{label}</span>
        <span className="flex items-center gap-1 text-gray-500">
          {value}
          <ChevronRight className="h-3.5 w-3.5 text-gray-300 group-hover:text-[#CC1414]" />
        </span>
      </div>
      <div className="h-2.5 overflow-hidden rounded-full bg-gray-100">
        <div className={`h-full rounded-full ${tone}`} style={{ width: `${width}%` }} />
      </div>
    </Link>
  );
}

type Slice = { label: string; value: number; color: string; href: string };

/** Where each count lives, so every number on the page opens its list. */
const LINKS = {
  orders: "/seller/orders",
  inProgress: "/seller/orders?status=in_progress",
  dispatched: "/seller/orders?status=dispatched",
  delivered: "/seller/orders?status=delivered",
  cancelled: "/seller/orders?status=cancelled",
  newRfqs: "/seller/quotations?tab=received",
  myBids: "/seller/quotations?tab=replied",
  closedRfqs: "/seller/quotations?tab=closed",
  wallet: "/wallet",
};

/**
 * A donut of one pipeline: every item sits in exactly one slice, so the slices
 * add up to the total in the middle. Colours match the bars beside it.
 */
function PipelineDonut({ title, total, slices }: { title: string; total: number; slices: Slice[] }) {
  const R = 40;
  const C = 2 * Math.PI * R;
  const lengths = slices.map((s) => (total > 0 ? (s.value / total) * C : 0));
  const starts = lengths.map((_, i) => lengths.slice(0, i).reduce((a, b) => a + b, 0));

  return (
    <figure className="flex flex-col items-center gap-4">
      <div className="relative h-32 w-32">
        <svg
          viewBox="0 0 100 100"
          className="h-full w-full -rotate-90"
          role="img"
          aria-label={`${title}: ${slices.map((s) => `${s.label} ${s.value}`).join(", ")}`}
        >
          <circle cx="50" cy="50" r={R} fill="none" stroke="#f3f4f6" strokeWidth="14" />
          {slices.map((s, i) =>
            lengths[i] > 0 ? (
              <circle
                key={s.label}
                cx="50"
                cy="50"
                r={R}
                fill="none"
                stroke={s.color}
                strokeWidth="14"
                strokeDasharray={`${lengths[i]} ${C - lengths[i]}`}
                strokeDashoffset={-starts[i]}
              />
            ) : null
          )}
        </svg>
        <div className="absolute inset-0 flex flex-col items-center justify-center">
          <span className="text-xl font-bold text-gray-900">{total}</span>
          <span className="text-[10px] uppercase tracking-wide text-gray-500">{title}</span>
        </div>
      </div>
      <figcaption className="w-full">
        <ul className="space-y-1.5 text-sm">
          {slices.map((s) => (
            <li key={s.label}>
              <Link href={s.href} className="group -mx-1.5 flex items-center justify-between gap-2 rounded-md px-1.5 py-0.5 hover:bg-gray-50">
                <span className="flex min-w-0 items-center gap-2 text-gray-700 group-hover:text-[#CC1414]">
                  <span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ backgroundColor: s.color }} />
                  <span className="truncate">{s.label}</span>
                </span>
                <span className="shrink-0 tabular-nums text-gray-900">
                  {s.value}
                  <span className="ml-1 text-xs text-gray-500">{total > 0 ? Math.round((s.value / total) * 100) : 0}%</span>
                </span>
              </Link>
            </li>
          ))}
        </ul>
      </figcaption>
    </figure>
  );
}

/* Catalog Health is hidden for now (the pipeline chart took its place); flip
   this to bring it back. */
const SHOW_CATALOG_HEALTH = false;

function CatalogHealth({ counts }: { counts: ApiSellerDashboard["counts"] }) {
  const inactiveProducts = Math.max(0, counts.products_total - counts.products_active);

  return (
    <div className="rounded-xl bg-white p-4 shadow-sm ring-1 ring-gray-100">
      <div className="mb-4 flex items-center justify-between">
        <div>
          <h2 className="text-base font-semibold text-gray-900">Catalog Health</h2>
          <p className="text-xs text-gray-500">How much of your catalog is live.</p>
        </div>
        <Package className="h-4 w-4 text-[#CC1414]" />
      </div>
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-[140px_1fr] sm:items-center">
        <div className="flex h-32 w-32 items-center justify-center rounded-full text-center"
          style={{
            background: `conic-gradient(#22c55e ${(counts.products_active / Math.max(counts.products_total || 1, 1)) * 360}deg, #e5e7eb 0deg)`,
          }}
        >
          <div className="flex h-22 w-22 flex-col items-center justify-center rounded-full bg-white" style={{height: '5.5rem', width: '5.5rem'}}>
            <span className="text-xl font-bold text-gray-900">{counts.products_total > 0 ? Math.round((counts.products_active / counts.products_total) * 100) : 0}%</span>
            <span className="text-[10px] uppercase tracking-wide text-gray-500">Active</span>
          </div>
        </div>
        <div className="space-y-4">
          <ProgressBar label="Active Products" value={counts.products_active} total={Math.max(counts.products_total, 1)} tone="bg-emerald-500" href="/seller/products" />
          <ProgressBar label="Inactive Products" value={inactiveProducts} total={Math.max(counts.products_total, 1)} tone="bg-gray-400" href="/seller/products" />
          <div className="rounded-lg bg-gray-50 px-4 py-3 text-sm text-gray-600 ring-1 ring-gray-100">
            {counts.products_total > 0
              ? `${counts.products_active} of ${counts.products_total} products are active and visible to buyers.`
              : "No products added yet. Add products to start receiving enquiries."}
          </div>
        </div>
      </div>
    </div>
  );
}

function fmtINR(n: number) {
  return new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", maximumFractionDigits: 0 }).format(n);
}

export default function SellerDashboard() {
  const { token, ready } = useToken();
  const [data, setData] = useState<ApiSellerDashboard | null>(null);
  const [err, setErr] = useState<string | null>(null);

  useEffect(() => {
    if (!ready || !token) return;
    sellerApi.dashboard(token).then(setData).catch((e) => setErr(e.message));
  }, [ready, token]);

  if (err) return <div className="rounded-xl bg-red-50 p-6 text-red-700 ring-1 ring-red-100">{err}</div>;
  if (!data) {
    return (
      <div className="rounded-xl bg-white p-10 shadow-sm ring-1 ring-gray-100">
        <Loader label="Loading dashboard…" />
      </div>
    );
  }

  const orders = data.tiles?.orders;
  const rfqs = data.tiles?.rfqs;
  const orderTotal = Math.max(orders?.total ?? data.counts.orders_total, 1);
  const rfqTotal = Math.max(rfqs?.total ?? 0, 1);
  const newRfqs = rfqs?.new ?? 0;
  // One new RFQ opens straight onto its rate form; several open the list.
  const quoteHref = newRfqs === 1 && data.recent_rfqs[0] ? `/seller/quotations/${data.recent_rfqs[0].id}` : LINKS.newRfqs;

  return (
    <div className="space-y-6">
      <header className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <h1 className="text-xl font-bold text-gray-900">Seller Dashboard</h1>
        <div className="flex flex-wrap gap-2">
          <Link href="/seller/products" className="inline-flex items-center gap-1.5 rounded-lg border border-[#CC1414] px-3 py-1.5 text-sm font-medium text-[#CC1414] hover:bg-red-50">
            <Package className="h-4 w-4" /> Products
          </Link>
          <Link href="/seller/quotations" className="inline-flex items-center gap-1.5 rounded-lg bg-[#CC1414] px-3 py-1.5 text-sm font-medium text-white hover:bg-[#a30f0f]">
            View RFQs
          </Link>
        </div>
      </header>

      {/* New RFQs are timed: say so at the top, with the way in. */}
      {newRfqs > 0 && (
        <Link
          href={quoteHref}
          className="flex flex-col gap-3 rounded-xl bg-gradient-to-r from-[#CC1414] to-[#e23b2e] p-4 text-white shadow-sm transition hover:shadow-md sm:flex-row sm:items-center sm:justify-between"
        >
          <span className="flex items-start gap-3">
            <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-white/15">
              <BellRing className="h-5 w-5 animate-pulse" />
            </span>
            <span>
              <span className="block text-base font-bold">
                {newRfqs === 1 ? "You have a new RFQ" : `You have ${newRfqs} new RFQs`}
              </span>
              <span className="block text-sm text-white/85">The bidding timer is running. Submit your rate before it ends.</span>
            </span>
          </span>
          <span className="inline-flex shrink-0 items-center justify-center gap-1.5 rounded-lg bg-white px-4 py-2 text-sm font-semibold text-[#CC1414]">
            {newRfqs === 1 ? "Submit rate" : "See new RFQs"} <ArrowRight className="h-4 w-4" />
          </span>
        </Link>
      )}

      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
        <StatCard label="Cash" value={fmtINR(data.wallet.cash_balance)} icon={IndianRupee} tone="bg-emerald-50 text-emerald-600" href={LINKS.wallet} />
        <StatCard label="Credit" value={fmtINR(data.wallet.credit_balance)} icon={Wallet} tone="bg-blue-50 text-blue-600" href={LINKS.wallet} />
        <StatCard
          label="New RFQs"
          value={newRfqs}
          icon={Inbox}
          tone="bg-purple-50 text-purple-600"
          href={quoteHref}
          flag={newRfqs > 0 ? "Quote now" : null}
        />
        <StatCard label="In progress" value={orders?.in_progress ?? 0} icon={Clock} tone="bg-orange-50 text-orange-600" href={LINKS.inProgress} />
        <StatCard label="Dispatched" value={orders?.dispatched ?? 0} icon={ShoppingBag} tone="bg-indigo-50 text-indigo-600" href={LINKS.dispatched} />
        <StatCard label="Payment due" value={fmtINR(orders?.payment_due_amount ?? 0)} icon={IndianRupee} tone="bg-red-50 text-red-600" href={LINKS.orders} />
      </div>

      {/* Prices are the daily job, so they come right after the numbers. */}
      {token && <SellerProductsCard token={token} />}

      <section className="grid grid-cols-1 gap-5 xl:grid-cols-2">
        <div className="rounded-xl bg-white p-4 shadow-sm ring-1 ring-gray-100">
          <div className="mb-4 flex items-center justify-between">
            <div>
              <h2 className="text-base font-semibold text-gray-900">Order Pipeline</h2>
              <p className="text-xs text-gray-500">
                {orders ? `${orders.total} orders · ${rfqs?.total ?? 0} RFQs you were invited to` : "Order and RFQ flow."}
              </p>
            </div>
            <ShoppingBag className="h-4 w-4 text-[#CC1414]" />
          </div>
          <div className="space-y-4">
            {/* Each group's bars sum to its total (B35): every order and every
                RFQ falls in exactly one bar. */}
            <ProgressBar label="Orders in progress" value={orders?.in_progress ?? 0} total={orderTotal} tone="bg-orange-400" href={LINKS.inProgress} />
            <ProgressBar label="Orders dispatched" value={orders?.dispatched ?? 0} total={orderTotal} tone="bg-indigo-500" href={LINKS.dispatched} />
            <ProgressBar label="Orders delivered" value={orders?.delivered ?? 0} total={orderTotal} tone="bg-emerald-500" href={LINKS.delivered} />
            <ProgressBar label="RFQs won" value={rfqs?.won ?? 0} total={rfqTotal} tone="bg-emerald-600" href={LINKS.myBids} />
            <ProgressBar label="Rates submitted (awaiting)" value={rfqs?.quoted ?? 0} total={rfqTotal} tone="bg-blue-500" href={LINKS.myBids} />
            <ProgressBar label="New RFQs to quote" value={newRfqs} total={rfqTotal} tone="bg-purple-500" href={LINKS.newRfqs} />
          </div>
        </div>

        <div className="rounded-xl bg-white p-4 shadow-sm ring-1 ring-gray-100">
          <div className="mb-4 flex items-center justify-between">
            <div>
              <h2 className="text-base font-semibold text-gray-900">Pipeline Breakdown</h2>
              <p className="text-xs text-gray-500">Where your orders and RFQs stand, by share.</p>
            </div>
            <PieChart className="h-4 w-4 text-[#CC1414]" />
          </div>
          <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
            <PipelineDonut
              title="Orders"
              total={orders?.total ?? 0}
              slices={[
                { label: "In progress", value: orders?.in_progress ?? 0, color: "#fb923c", href: LINKS.inProgress },
                { label: "Dispatched", value: orders?.dispatched ?? 0, color: "#6366f1", href: LINKS.dispatched },
                { label: "Delivered", value: orders?.delivered ?? 0, color: "#10b981", href: LINKS.delivered },
                ...(orders?.cancelled ? [{ label: "Cancelled", value: orders.cancelled, color: "#9ca3af", href: LINKS.cancelled }] : []),
              ]}
            />
            <PipelineDonut
              title="RFQs"
              total={rfqs?.total ?? 0}
              slices={[
                { label: "Won", value: rfqs?.won ?? 0, color: "#059669", href: LINKS.myBids },
                { label: "Awaiting", value: rfqs?.quoted ?? 0, color: "#3b82f6", href: LINKS.myBids },
                { label: "New to quote", value: newRfqs, color: "#a855f7", href: LINKS.newRfqs },
                ...(rfqs?.lost ? [{ label: "Lost", value: rfqs.lost, color: "#f87171", href: LINKS.myBids }] : []),
                ...(rfqs?.closed ? [{ label: "Closed", value: rfqs.closed, color: "#9ca3af", href: LINKS.closedRfqs }] : []),
              ]}
            />
          </div>
        </div>

        {SHOW_CATALOG_HEALTH && <CatalogHealth counts={data.counts} />}
      </section>

      <section className="grid grid-cols-1 gap-5 lg:grid-cols-2">
        <div className="rounded-xl bg-white p-4 shadow-sm ring-1 ring-gray-100">
          <div className="mb-3 flex items-center justify-between">
            <h2 className="text-base font-semibold text-gray-900">Recent Orders</h2>
            <Link href="/seller/orders" className="flex items-center gap-1 text-xs text-[#CC1414] hover:underline">View all <ArrowRight className="h-3 w-3" /></Link>
          </div>
          {data.recent_orders.length === 0 ? (
            <p className="py-6 text-center text-sm text-gray-500">No orders yet.</p>
          ) : (
            <ul className="divide-y divide-gray-100">
              {data.recent_orders.map((o) => (
                <li key={o.id}>
                  <Link href={`/seller/orders/${o.id}`} className="group -mx-2 flex items-center justify-between gap-3 rounded-lg px-2 py-3 hover:bg-gray-50">
                    <div className="min-w-0">
                      <p className="truncate text-sm font-medium text-gray-900 group-hover:text-[#CC1414]">{o.product?.name ?? "—"}</p>
                      <p className="truncate text-xs text-gray-500">
                        {o.order_id ?? o.unique_id} · {o.customer?.name ?? "—"} · {o.status_label ?? o.status}
                      </p>
                    </div>
                    <span className="flex shrink-0 items-center gap-1 text-sm font-semibold text-gray-900">
                      {fmtINR(o.final_amount || o.total_amount)}
                      <ChevronRight className="h-4 w-4 text-gray-300 group-hover:text-[#CC1414]" />
                    </span>
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </div>

        <div className={`rounded-xl bg-white p-4 shadow-sm ring-1 ${newRfqs > 0 ? "ring-[#CC1414]/40" : "ring-gray-100"}`}>
          <div className="mb-3 flex items-center justify-between">
            <h2 className="flex items-center gap-2 text-base font-semibold text-gray-900">
              New RFQs
              {newRfqs > 0 && (
                <span className="rounded-full bg-[#CC1414] px-2 py-0.5 text-[10px] font-bold text-white">{newRfqs}</span>
              )}
            </h2>
            <Link href={LINKS.newRfqs} className="flex items-center gap-1 text-xs text-[#CC1414] hover:underline">View all <ArrowRight className="h-3 w-3" /></Link>
          </div>
          {data.recent_rfqs.length === 0 ? (
            <div className="py-6 text-center text-sm text-gray-500">
              <Inbox className="mx-auto mb-2 h-6 w-6 text-gray-300" />
              No new RFQs right now. We will notify you the moment one arrives.
            </div>
          ) : (
            <ul className="space-y-2">
              {data.recent_rfqs.map((r) => (
                <li key={r.id}>
                  <Link
                    href={`/seller/quotations/${r.id}`}
                    className="group flex items-center justify-between gap-3 rounded-lg border border-gray-100 p-3 transition hover:border-[#CC1414]/40 hover:bg-red-50/40"
                  >
                    <div className="min-w-0">
                      <p className="flex items-center gap-2">
                        <span className="truncate text-sm font-semibold text-gray-900 group-hover:text-[#CC1414]">{r.product?.name ?? "—"}</span>
                        {r.bidding?.is_live && (
                          <span className="inline-flex shrink-0 items-center gap-1 rounded-full bg-amber-50 px-1.5 py-0.5 text-[10px] font-semibold text-amber-800 ring-1 ring-amber-200">
                            <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-amber-600" /> LIVE
                          </span>
                        )}
                      </p>
                      <p className="mt-0.5 flex flex-wrap items-center gap-x-2 text-xs text-gray-500">
                        <span>{r.unique_id}</span>
                        {r.quantity ? <span>{r.quantity} {r.unit_label ?? ""}</span> : null}
                        {r.delivery_city && (
                          <span className="inline-flex items-center gap-0.5">
                            <MapPin className="h-3 w-3" /> {r.delivery_city}
                          </span>
                        )}
                      </p>
                      {r.bidding?.is_live && (
                        <p className="mt-0.5 text-xs text-gray-500">
                          Ends in{" "}
                          <Countdown endsAt={r.bidding.ends_at} fallbackSeconds={r.bidding.seconds_left} className="font-semibold text-[#CC1414]" />
                        </p>
                      )}
                    </div>
                    <span className="inline-flex shrink-0 items-center gap-1 rounded-lg bg-[#CC1414] px-3 py-1.5 text-xs font-semibold text-white group-hover:bg-[#a30f0f]">
                      Submit rate <ChevronRight className="h-3.5 w-3.5" />
                    </span>
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </div>
      </section>
    </div>
  );
}
