'use client';

import React, { useState } from 'react';
import { Layers, CheckCircle2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Modal } from '@/components/ui/modal';
import { useEligibleCoupons, useAssignCoupons } from '@/services/purchase-orders/queries';
import { PurchaseOrderRecord } from '@/services/purchase-orders/types';

interface Props {
  po: PurchaseOrderRecord;
  onClose: () => void;
}

export default function AssignCouponsModal({ po, onClose }: Props) {
  const { data: eligible, isLoading } = useEligibleCoupons(po.id, true);
  const [selected, setSelected] = useState<string[]>([]);
  const assignMutation = useAssignCoupons();

  const toggle = (id: string) => {
    setSelected((prev) => {
      if (prev.includes(id)) return prev.filter((x) => x !== id);
      if (prev.length >= po.quantityAsked) return prev; // cap at requested quantity
      return [...prev, id];
    });
  };

  const handleAutoAssign = async () => {
    try {
      await assignMutation.mutateAsync({ id: po.id });
      onClose();
    } catch {
      // handled by mutation toast
    }
  };

  const handleAssignSelected = async () => {
    try {
      await assignMutation.mutateAsync({ id: po.id, couponIds: selected });
      onClose();
    } catch {
      // handled by mutation toast
    }
  };

  return (
    <Modal onClose={onClose} icon={Layers} iconClassName="text-primary" title={`Assign Coupons — ${po.poNumber}`}>
      <div className="p-4 space-y-4">
        <div className="p-2.5 rounded-lg bg-muted/30 border border-border/40 text-[11px] font-medium text-foreground flex items-center justify-between">
          <span>Requested Quantity</span>
          <span className="font-bold">{po.quantityAsked}</span>
        </div>

        {isLoading ? (
          <p className="text-xs text-muted-foreground text-center py-6">Loading eligible coupons…</p>
        ) : !eligible || eligible.length === 0 ? (
          <p className="text-xs text-muted-foreground text-center py-6">
            No eligible coupons currently sit in the source pool for this purchase order.
          </p>
        ) : (
          <div className="max-h-72 overflow-y-auto space-y-1.5 border border-border/40 rounded-lg p-2">
            {eligible.map((c) => {
              const isSelected = selected.includes(c.id);
              return (
                <button
                  type="button"
                  key={c.id}
                  onClick={() => toggle(c.id)}
                  className={`w-full flex items-center justify-between p-2 rounded-lg border text-xs font-mono transition-colors ${
                    isSelected
                      ? 'border-primary bg-primary/10 text-primary'
                      : 'border-border/40 bg-background text-foreground hover:bg-muted/30'
                  }`}
                >
                  <span>{c.code}</span>
                  {isSelected && <CheckCircle2 className="h-3.5 w-3.5" />}
                </button>
              );
            })}
          </div>
        )}

        <p className="text-[10px] text-muted-foreground/60">
          Pick exactly {po.quantityAsked} coupon(s) manually, or let the system auto-assign the oldest eligible
          coupons on a first-in-first-out basis.
        </p>

        <div className="flex items-center justify-end gap-2 border-t border-border/10 pt-3">
          <Button type="button" variant="ghost" onClick={onClose} className="h-8 rounded-lg px-3 text-xs font-semibold">
            Cancel
          </Button>
          <Button
            type="button"
            variant="outline"
            disabled={assignMutation.isPending}
            onClick={handleAutoAssign}
            className="h-8 rounded-lg px-3 text-xs font-semibold"
          >
            Auto-Assign (FIFO)
          </Button>
          <Button
            type="button"
            disabled={assignMutation.isPending || selected.length !== po.quantityAsked}
            onClick={handleAssignSelected}
            className="h-8 rounded-lg px-3 text-xs font-semibold shadow-sm"
          >
            Assign Selected ({selected.length}/{po.quantityAsked})
          </Button>
        </div>
      </div>
    </Modal>
  );
}
