"use client";

import { useState } from "react";
import { Info } from "lucide-react";

import { formatAmount } from "@/lib/pricing/forPrice";
import type { ApiProductPricing } from "@/lib/api/types";

/**
 * The Ex-Works row of the price card, with an "i" that opens how the number was
 * arrived at.
 *
 * The whole row lives here rather than just the button: the panel has to sit
 * under the row, and a disclosure rendered inside the `<dt>` would be boxed into
 * the label column.
 */
export default function ExPriceBreakup({
  pricing,
  unit,
  originCity,
}: {
  pricing: ApiProductPricing;
  unit: string;
  /** Where the goods load from — the Ex-Works price belongs to that city. */
  originCity?: string | null;
}) {
  const [open, setOpen] = useState(false);

  const rows: { label: string; value: number }[] = [
    { label: "Base Price", value: pricing.base_price },
    { label: "Gauge Difference", value: pricing.gauge_diff },
    { label: "Loading", value: pricing.loading_charge },
    { label: "Insurance", value: pricing.insurance_charge },
    { label: "Quality Charge", value: pricing.quality_charge },
    ...(pricing.extra_charges ? [{ label: "Other Charges", value: pricing.extra_charges }] : []),
    { label: `GST (${pricing.gst}%)`, value: pricing.tax_amount },
    ...(pricing.tcs ? [{ label: "TCS", value: pricing.tcs }] : []),
  ];

  return (
    <div>
      <div className="flex justify-between">
        <dt className="text-gray-500">
          Ex-Works Price{originCity ? ` (${originCity})` : ""}
          <button
            type="button"
            onClick={() => setOpen((prev) => !prev)}
            aria-expanded={open}
            aria-label="How the Ex-Works price is calculated"
            className="ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full align-middle text-gray-400 transition hover:bg-gray-100 hover:text-[#CC1414]"
          >
            <Info size={12} />
          </button>
        </dt>
        <dd className="font-medium text-gray-900">{formatAmount(pricing.ex_works_price)}</dd>
      </div>

      {open && (
        <div className="mt-2 space-y-1 rounded-lg bg-gray-50 p-2.5 text-[11px]">
          {rows.map((row) => (
            <div key={row.label} className="flex justify-between gap-3">
              <span className="text-gray-500">{row.label}</span>
              <span className="font-medium text-gray-700">{formatAmount(row.value)}</span>
            </div>
          ))}
          <div className="flex justify-between gap-3 border-t border-gray-200 pt-1">
            <span className="font-semibold text-gray-700">Ex-Works Price (per {unit})</span>
            <span className="font-bold text-gray-900">{formatAmount(pricing.ex_works_price)}</span>
          </div>
        </div>
      )}
    </div>
  );
}
