'use client';

import { useFieldArray, useFormContext } from 'react-hook-form';
import { Plus, Trash2 } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CurrencyInput } from '@/components/shared/currency-input';
import { formatCurrency } from '@/lib/utils/currency';

interface LineItem {
  description: string;
  quantity: number;
  unitPrice: number;
}

interface InvoiceLineItemsProps {
  name?: string;
  /** Currency code from the parent invoice form (drives both the
   *  unit-price input symbol and the subtotal formatting). */
  currency?: string;
}

export function InvoiceLineItems({ name = 'lineItems', currency = 'USD' }: InvoiceLineItemsProps) {
  const { register, setValue, watch } = useFormContext();
  const { fields, append, remove } = useFieldArray({ name });

  const lineItems: LineItem[] = watch(name) ?? [];

  const subtotal = lineItems.reduce(
    (sum, li) => sum + (Number(li.quantity) || 0) * (Number(li.unitPrice) || 0),
    0,
  );

  return (
    <div className="space-y-3">
      {/* Header */}
      {fields.length > 0 && (
        <div className="grid grid-cols-12 gap-2 text-xs font-medium text-muted-foreground px-1">
          <span className="col-span-6">Description</span>
          <span className="col-span-2 text-right">Qty</span>
          <span className="col-span-2 text-right">Unit Price</span>
          <span className="col-span-1 text-right">Total</span>
          <span className="col-span-1" />
        </div>
      )}

      {/* Line items */}
      {fields.map((field, index) => {
        const qty = Number(lineItems[index]?.quantity) || 0;
        const price = Number(lineItems[index]?.unitPrice) || 0;
        const lineTotal = qty * price;

        return (
          <div key={field.id} className="grid grid-cols-12 gap-2 items-start">
            <div className="col-span-6">
              <Input
                {...register(`${name}.${index}.description`)}
                placeholder="Description"
                className="h-8 text-sm"
              />
            </div>
            <div className="col-span-2">
              <Input
                {...register(`${name}.${index}.quantity`, { valueAsNumber: true })}
                type="number"
                min="0.001"
                step="any"
                placeholder="1"
                className="h-8 text-sm text-right"
              />
            </div>
            <div className="col-span-2">
              <CurrencyInput
                value={lineItems[index]?.unitPrice ?? null}
                currency={currency}
                onChange={(v) =>
                  setValue(`${name}.${index}.unitPrice`, v ?? 0, { shouldDirty: true })
                }
                step="any"
                className="h-8 text-sm text-right"
              />
            </div>
            <div className="col-span-1 flex items-center justify-end h-8">
              <span className="text-sm tabular-nums">{formatCurrency(lineTotal, currency)}</span>
            </div>
            <div className="col-span-1 flex items-center justify-end h-8">
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="h-7 w-7 text-muted-foreground hover:text-destructive"
                onClick={() => remove(index)}
              >
                <Trash2 className="h-3.5 w-3.5" />
              </Button>
            </div>
          </div>
        );
      })}

      {/* Empty state */}
      {fields.length === 0 && (
        <p className="text-sm text-muted-foreground py-4 text-center border border-dashed rounded-md">
          No line items yet. Add your first item below.
        </p>
      )}

      {/* Add button + subtotal */}
      <div className="flex items-center justify-between pt-1">
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={() => append({ description: '', quantity: 1, unitPrice: 0 })}
        >
          <Plus className="mr-1.5 h-3.5 w-3.5" />
          Add Line Item
        </Button>
        {fields.length > 0 && (
          <div className="text-sm font-medium">
            Subtotal: <span className="tabular-nums">{formatCurrency(subtotal, currency)}</span>
          </div>
        )}
      </div>
    </div>
  );
}
