"use client";

import { useState, useEffect, useRef } from "react";
import {
  type WholesaleCustomer,
  type WholesaleProduct,
} from "@/actions/wholesale";
import { getWholesaleCustomerPricing, upsertWholesaleCustomerPricing, deleteWholesaleCustomerPricing } from "@/actions/wholesale-register";
import { AdminButton } from "@/components/admin/design-system";

export default function CustomerPricingPanel({ customer, products, onClose, onMsg }: {
  customer: WholesaleCustomer;
  products: WholesaleProduct[];
  onClose: () => void;
  onMsg: (kind: "success" | "error", text: string) => void;
}) {
  const [overrides, setOverrides] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(true);
  const [saving] = useState(false);
  const dialogRef = useRef<HTMLDialogElement | null>(null);

  useEffect(() => {
    const dialog = dialogRef.current;
    if (!dialog) return;
    if (!dialog.open) dialog.showModal();
    const onCancel = (e: Event) => {
      e.preventDefault();
      onClose();
    };
    dialog.addEventListener("cancel", onCancel);
    return () => {
      dialog.removeEventListener("cancel", onCancel);
    };
  }, [onClose]);

  useEffect(() => {
    getWholesaleCustomerPricing(customer.id).then(pricing => {
      const map: Record<string, string> = {};
      for (const p of pricing) {
        map[p.product_id] = p.custom_unit_price.toString();
      }
      setOverrides(map);
      setLoading(false);
    });
  }, [customer.id]);

  async function handleSave(productId: string, price: string) {
    if (!price || isNaN(Number(price))) {
      await deleteWholesaleCustomerPricing({ customerId: customer.id, productId });
      setOverrides(prev => { const n = { ...prev }; delete n[productId]; return n; });
    } else {
      await upsertWholesaleCustomerPricing({ customerId: customer.id, productId, customUnitPrice: Number(price) });
      setOverrides(prev => ({ ...prev, [productId]: price }));
    }
    onMsg("success", "Pricing updated.");
  }

  return (
    <dialog
      ref={dialogRef}
      aria-label="Pricing overrides"
      className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 m-0 p-0 max-w-none max-h-none w-full h-full backdrop:bg-black/40"
    >
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-2xl max-h-[80vh] overflow-hidden flex flex-col border border-[var(--admin-border)]">
        <div className="px-6 py-4 border-b border-[var(--admin-border)] flex items-center justify-between">
          <div>
            <h2 className="text-lg font-bold text-[var(--admin-text-primary)]">Pricing Overrides</h2>
            <p className="text-sm text-[var(--admin-text-muted)]">{customer.company_name}</p>
          </div>
          <button type="button" onClick={onClose} aria-label="Close pricing overrides" className="text-[var(--admin-text-muted)] hover:text-[var(--admin-text-secondary)]">
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="overflow-y-auto flex-1 px-6 py-4">
          {loading ? (
            <p className="text-[var(--admin-text-muted)] text-sm">Loading...</p>
          ) : products.length === 0 ? (
            <p className="text-[var(--admin-text-muted)] text-sm">No products available. Add wholesale products to see them here.</p>
          ) : (
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-[var(--admin-text-muted)] border-b">
                  <th className="pb-2 font-medium">Product</th>
                  <th className="pb-2 font-medium">Standard Price</th>
                  <th className="pb-2 font-medium">Override Price</th>
                  <th className="pb-2" aria-label="Actions"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[var(--admin-border-light)]">
                {products.map(p => {
                  const standardPrice = p.price_tiers?.[0]?.price ?? 0;
                  const overridePrice = overrides[p.id] ?? "";
                  return (
                    <tr key={p.id}>
                      <td className="py-2.5 font-medium text-[var(--admin-text-primary)]">{p.name}</td>
                      <td className="py-2.5 text-[var(--admin-text-muted)]">${standardPrice.toFixed(2)}</td>
                      <td className="py-2.5">
                        <div className="flex items-center gap-2">
                          <span className="text-xs text-[var(--admin-text-muted)]">$</span>
                          <input aria-label="Number"
                            type="number"
                            step="0.01"
                            min="0"
                            value={overridePrice}
                            onChange={e => setOverrides(prev => ({ ...prev, [p.id]: e.target.value }))}
                            placeholder={standardPrice.toFixed(2)}
                            className="w-24 rounded-lg border border-[var(--admin-border)] px-2 py-1 text-sm outline-none focus:border-[var(--admin-accent)]"
                          />
                          {overridePrice && overridePrice !== standardPrice.toFixed(2) && (
                            <span className="text-xs text-[var(--admin-accent)] font-medium">Custom</span>
                          )}
                        </div>
                      </td>
                      <td className="py-2.5">
                        <AdminButton
                          variant="primary"
                          size="sm"
                          onClick={() => handleSave(p.id, overrides[p.id] ?? "")}
                          disabled={saving}
                        >
                          Save
                        </AdminButton>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
          <p className="mt-3 text-xs text-[var(--admin-text-muted)]">
            Leave override price blank to remove custom pricing and use standard price tiers.
          </p>
        </div>
      </div>
    </dialog>
  );
}
