"use client";

import { AlertTriangle, Loader2 } from "lucide-react";
import type { WidgetItem, AllocationSlice } from "@/types/dashboard";
import { AllocationChart, DEFAULT_CHART_HEIGHT } from "./AllocationChart";
import { ModalShell } from "@/components/ui/ModalShell";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";

export interface WidgetModalProps {
  widget: WidgetItem;
  allocationData: AllocationSlice[] | null;
  allocationError: string | null;
  allocationLoading?: boolean;
  modalChartData: AllocationSlice[];
  currency?: string;
  piePalette: string[];
  onClose: () => void;
}

/**
 * Widget detail dialog.
 *
 * Rebuilt on `ModalShell`. It previously hand-rolled `role="dialog"` and
 * `aria-modal` on a plain div, which announces as a dialog to screen readers
 * without actually behaving like one — no focus containment, no Escape, no
 * scroll lock, and the close control was a text button styled as a chip.
 *
 * The chart panel's three states (loading / error / no data) were three
 * differently-styled boxes; they are consistent now, and the loading state is a
 * skeleton of the chart rather than the words "Loading chart…".
 */
export function WidgetModal({
  widget,
  allocationError,
  allocationLoading = false,
  modalChartData,
  currency,
  piePalette,
  onClose,
}: WidgetModalProps) {
  const isAssetAllocation = widget.file_path === "asset_allocation";
  const chartTitle = isAssetAllocation ? "Asset allocation" : "Category coverage";
  const showError = Boolean(allocationError && isAssetAllocation);
  const hasChartData = modalChartData.length > 0;
  const showChartPanel =
    !isAssetAllocation || allocationLoading || showError || hasChartData;

  const summary = [
    { label: "File", value: widget.file_path || "—" },
    { label: "Added", value: new Date(widget.date_added).toLocaleDateString() },
    { label: "ISIN", value: widget.isin || "—" },
    {
      label: "Description",
      value: widget.short_description || "No description provided.",
    },
  ];

  return (
    <ModalShell
      isOpen
      onClose={onClose}
      size="lg"
      eyebrow="Widget"
      title={widget.name}
      description={`Category ${widget.category_id} · Priority ${widget.priority ?? "—"}`}
    >
      <div className="mb-4 flex flex-wrap items-center gap-2">
        <Badge variant={widget.status ? "success" : "secondary"}>
          {widget.status ? "Active" : "Inactive"}
        </Badge>
      </div>

      <div className={cn("grid grid-cols-1 gap-4", showChartPanel && "lg:grid-cols-2")}>
        <Card className="gap-0 bg-muted/40 py-4 shadow-none">
          <CardContent className="px-4">
            <p className="oxy-eyebrow mb-3">Summary</p>
            <dl className="grid grid-cols-2 gap-x-4 gap-y-3">
              {summary.map((item) => (
                <div key={item.label} className="min-w-0">
                  <dt className="text-xs text-muted-foreground">{item.label}</dt>
                  <dd className="mt-0.5 text-sm font-medium break-words text-foreground">
                    {item.value}
                  </dd>
                </div>
              ))}
            </dl>
          </CardContent>
        </Card>

        {showChartPanel && (
          <Card className="gap-0 py-4 shadow-none">
            <CardContent className="px-4">
              <p className="oxy-eyebrow mb-3">{chartTitle}</p>

              {isAssetAllocation && allocationLoading ? (
                <div
                  className="flex h-56 flex-col items-center justify-center gap-3"
                  role="status"
                  aria-live="polite"
                >
                  <Skeleton className="size-32 rounded-full" />
                  <Loader2 className="size-4 animate-spin text-muted-foreground" aria-hidden />
                  <span className="sr-only">Loading chart…</span>
                </div>
              ) : showError ? (
                <div className="flex h-56 flex-col items-center justify-center gap-2 rounded-md bg-warning-soft px-4 text-center">
                  <AlertTriangle className="size-5 text-warning" aria-hidden />
                  <p className="text-xs leading-relaxed text-warning">{allocationError}</p>
                </div>
              ) : !hasChartData ? (
                <div className="flex h-56 items-center justify-center rounded-md bg-muted">
                  <p className="text-xs text-muted-foreground">No chart data available.</p>
                </div>
              ) : (
                <AllocationChart
                  slices={modalChartData}
                  currency={currency}
                  piePalette={piePalette}
                  height={DEFAULT_CHART_HEIGHT}
                />
              )}
            </CardContent>
          </Card>
        )}
      </div>
    </ModalShell>
  );
}
