"use client";

import { useState } from "react";
import { Card } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import {
  useDashboardPipelineQuery,
  type PipelineModule,
} from "@/features/dashboard/hooks/use-dashboard-section-queries";
import { isDashboardSectionLoading } from "@/features/dashboard/hooks/dashboard-query-status";

const MODULES: { value: PipelineModule; label: string }[] = [
  { value: "Lead", label: "Leads" },
  { value: "Deal", label: "Deals" },
];

export function PipelineCard() {
  const [module, setModule] = useState<PipelineModule>("Lead");

  // Omit pipelineId so the API aggregates counts across every pipeline for the chosen module.
  const { data: pipelineData, isPending, isFetching } = useDashboardPipelineQuery({
    module,
  });
  const showSkeleton = isDashboardSectionLoading(
    isPending,
    isFetching,
    pipelineData,
  );

  if (showSkeleton) return <PipelineCardSkeleton />;

  const stages = pipelineData.stages ?? [];
  const totalDeals = stages.reduce((sum, s) => sum + s.count, 0);

  return (
    <Card className="gap-0 p-5 h-full overflow-hidden flex flex-col">
      {/* Header */}
      <div className="flex items-start justify-between mb-3">
        <div className="flex flex-col">
          <h3 className="text-[13px] font-bold text-text font-['Lexend']">
            Pipeline
          </h3>
          <p className="text-[11px] text-gray-700 font-normal mt-0.5">
            All pipelines · Count by stage · All time
          </p>
        </div>

        {/* Leads / Deals module toggle */}
        <div className="flex items-center bg-border/40 rounded-lg p-0.5 gap-0.5">
          {MODULES.map((m) => (
            <button
              key={m.value}
              type="button"
              onClick={() => setModule(m.value)}
              className={cn(
                "px-3 py-1 rounded-md text-[11px] font-semibold transition-all",
                module === m.value
                  ? "bg-accent text-white shadow-sm"
                  : "text-gray-600 hover:text-text",
              )}
            >
              {m.label}
            </button>
          ))}
        </div>
      </div>

      {/* Stages — all pipelines combined; module toggle switches Lead vs Deal stages */}
      {stages.length === 0 ? (
        <div className="flex flex-1 items-center justify-center py-8">
          <p className="text-[12px] text-gray-500">No data found</p>
        </div>
      ) : (
        <div className="flex flex-col gap-[11px] flex-1">
          {stages.map((item) => (
            <div key={item.stage} className="flex flex-col gap-[4px]">
              <div className="flex justify-between items-center px-0.5">
                <span className="text-xs font-medium text-text">
                  {item.stage}
                </span>
                <span className="text-[11px] text-gray-700 font-['Lexend_Deca']">
                  {item.count} {module === "Lead" ? "leads" : "deals"}
                </span>
              </div>
              <div className="h-[7px] bg-border rounded-full overflow-hidden">
                <div
                  className="h-full rounded-full transition-all duration-700 ease-in-out"
                  style={{ width: `${item.pct}%`, backgroundColor: item.fill }}
                />
              </div>
            </div>
          ))}
        </div>
      )}

      <div className="mt-4 pt-3 border-t border-border flex justify-between items-center">
        <span className="text-[11px] text-gray-700">
          Total Active {module === "Lead" ? "Leads" : "Deals"}
        </span>
        <span className="text-[13px] font-bold text-text font-['Lexend_Deca']">
          {totalDeals.toLocaleString()}
        </span>
      </div>
    </Card>
  );
}

export function PipelineCardSkeleton() {
  return (
    <Card className="gap-0 p-5 h-full overflow-hidden">
      <div className="flex justify-between items-start mb-3">
        <div className="flex flex-col gap-2">
          <Skeleton className="h-4 w-20 rounded-md bg-gradient-to-r from-accent/70 via-accent/40 to-border/50" />
          <Skeleton className="h-3 w-36 rounded-md bg-border/70" />
        </div>
        <Skeleton className="h-7 w-28 rounded-lg bg-border/60" />
      </div>
      <div className="flex flex-col gap-[11px] flex-1">
        {[1, 2, 3, 4, 5].map((i) => (
          <div key={i} className="flex flex-col gap-[6px]">
            <div className="flex justify-between items-center px-0.5">
              <Skeleton className="h-3 w-24 rounded-md bg-border/70" />
              <Skeleton className="h-3 w-14 rounded-md bg-border/60" />
            </div>
            <Skeleton className="h-[7px] w-full rounded-full bg-border/50" />
          </div>
        ))}
      </div>
      <div className="mt-4 pt-3 border-t border-border flex justify-between items-center">
        <Skeleton className="h-3 w-28 rounded-md bg-border/60" />
        <Skeleton className="h-4 w-16 rounded-md bg-border/60" />
      </div>
    </Card>
  );
}
