/**
 * New GRN Page
 * Create a new GRN (Goods Received Note)
 */

'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useForm, useFieldArray } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { procurementAPI } from '@/lib/api/procurement';
import { productsAPI } from '@/lib/api/products';
import { Button, Card, CardHeader, CardTitle, CardContent, Input } from '@/components/ui';
import { ArrowLeft, Plus, Trash2 } from 'lucide-react';
import toast from 'react-hot-toast';
import { formatCurrency } from '@/lib/utils/format';

const grnItemSchema = z.object({
  product_id: z.number().int().positive(),
  variant_id: z.number().int().positive().optional(),
  quantity: z.number().nonnegative().optional(), // Quantity for special items RM (optional for dimension-based RM)
  piece_length: z.number().nonnegative().optional(), // For dimension-based RM (can be 0 if not from PO)
  piece_width: z.number().nonnegative().optional(), // For dimension-based RM (can be 0 if not from PO)
  dimension_unit: z.enum(['inch', 'cm', 'm']).optional().or(z.literal('')), // For dimension-based RM (can be empty if not from PO)
  pieces_count: z.number().int().nonnegative().optional(), // For dimension-based RM
  ordered_quantity: z.number().nonnegative().optional(), // For tracking ordered vs received
  unit_cost: z.number().nonnegative(),
  from_po: z.boolean().optional(), // Flag to mark if item is from PO
  ordered_pieces: z.number().nonnegative().optional(),
  received_pieces: z.number().nonnegative().optional(),
  remaining_pieces: z.number().nonnegative().optional(),
});

const grnSchema = z.object({
  purchase_order_id: z.number().int().positive().optional(),
  vendor_id: z.number().int().positive().optional(),
  received_at: z.string().min(1, 'Received date is required'),
  items: z.array(grnItemSchema).min(1, 'At least one item is required')
    .refine((items) => items.some((item) => {
      // For dimension-based RM, check pieces_count; for others, check quantity
      const hasQuantity = (item.quantity || 0) > 0;
      const hasPieces = (item.pieces_count || 0) > 0;
      return hasQuantity || hasPieces;
    }), {
      message: 'At least one item must have a received quantity or pieces count greater than 0',
      path: ['items'],
    }),
  notes: z.string().optional(),
});

export default function NewGRNPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const queryClient = useQueryClient();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const prefillPoId = searchParams.get('purchase_order_id');

  // Fetch purchase orders
  const { data: posData } = useQuery({
    queryKey: ['purchase-orders'],
    queryFn: async () => {
      const response = await procurementAPI.listPurchaseOrders({ limit: 100 });
      return response.data || response;
    },
  });

  // Fetch PO details if prefill from URL
  const { data: poData } = useQuery({
    queryKey: ['purchase-order', prefillPoId],
    queryFn: async () => {
      if (!prefillPoId) return null;
      const response = await procurementAPI.getPurchaseOrder(parseInt(prefillPoId));
      return response?.data || response;
    },
    enabled: !!prefillPoId,
  });


  // Fetch vendors
  const { data: vendorsData } = useQuery({
    queryKey: ['vendors'],
    queryFn: async () => {
      const response = await procurementAPI.listVendors({ limit: 100 });
      return response.data || response;
    },
  });

  // Fetch products
  const { data: productsData } = useQuery({
    queryKey: ['products'],
    queryFn: async () => {
      const response = await productsAPI.list({ limit: 100 });
      return response.data || response;
    },
  });

  const purchaseOrders = posData?.purchaseOrders || posData?.purchase_orders || [];
  const vendors = vendorsData?.vendors || [];
  const products = productsData?.products || [];

  const {
    register,
    handleSubmit,
    control,
    watch,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(grnSchema),
    defaultValues: {
      purchase_order_id: prefillPoId ? parseInt(prefillPoId) : undefined,
      vendor_id: undefined,
      received_at: new Date().toISOString().split('T')[0],
      items: [{ product_id: 0, quantity: 0, unit_cost: 0 }],
    },
  });

  const watchedPoId = watch('purchase_order_id');

  // Fetch PO when selected from dropdown (if different from URL param)
  const { data: selectedPoData } = useQuery({
    queryKey: ['purchase-order', watchedPoId],
    queryFn: async () => {
      if (!watchedPoId || watchedPoId === prefillPoId) return null;
      const response = await procurementAPI.getPurchaseOrder(watchedPoId);
      return response?.data || response;
    },
    enabled: !!watchedPoId && watchedPoId !== prefillPoId,
  });

  // Use poData if from URL param, otherwise use selectedPoData
  const currentPoData = poData || selectedPoData;

  // Pre-fill vendor, received date, and items when PO is selected
  useEffect(() => {
    if (currentPoData) {
      // Pre-fill vendor
      if (currentPoData.vendor_id) {
        setValue('vendor_id', currentPoData.vendor_id);
      }

      // Set received date to current date (editable)
      setValue('received_at', new Date().toISOString().split('T')[0]);

      // Pre-fill items if PO has items
      if (currentPoData.items && Array.isArray(currentPoData.items) && currentPoData.items.length > 0) {
        // Load all items from PO with ordered quantity, received quantity, and remaining quantity
        // Only show items that still have remaining quantity to receive
        const poItems = currentPoData.items
          .filter((item) => {
            // Only include items that have remaining quantity > 0
            const remaining = item.remaining_quantity !== undefined 
              ? parseFloat(item.remaining_quantity) 
              : parseFloat(item.quantity) - (parseFloat(item.received_quantity) || 0);
            return remaining > 0;
          })
          .map((item) => {
            const orderedQty = parseFloat(item.quantity) || 0;
            const receivedQty = parseFloat(item.received_quantity) || 0;
            const remainingQty = item.remaining_quantity !== undefined
              ? parseFloat(item.remaining_quantity)
              : Math.max(0, orderedQty - receivedQty);
            
            const productId = item.product_id || item.product?.id || 0;
            const product = products.find(p => p.id === productId);
            const isDimBased = product?.product_type === 'RM' && product?.track_by_dimensions === true;
            
            const baseItem = {
              product_id: productId,
              variant_id: item.variant_id || item.variant?.id || undefined,
              ordered_quantity: orderedQty, // Total ordered
              received_quantity: receivedQty, // Already received in previous GRNs
              remaining_quantity: remainingQty, // Available to receive
              unit_cost: parseFloat(item.unit_cost) || 0, // Pre-fill from PO
            };
            
            // For dimension-based RM, ALWAYS pre-fill dimension fields from PO (they are REQUIRED and IMMUTABLE)
            if (isDimBased) {
              const orderedPieces = item.pieces_count || orderedQty;
              const receivedPieces = parseFloat(item.received_quantity) || 0; // Already received pieces
              const remainingPieces = remainingQty; // Remaining pieces to receive
              
              return {
                ...baseItem,
                piece_length: item.piece_length ? parseFloat(item.piece_length) : 0, // Pre-fill from PO (immutable)
                piece_width: item.piece_width ? parseFloat(item.piece_width) : 0, // Pre-fill from PO (immutable)
                dimension_unit: item.dimension_unit || '', // Pre-fill from PO (immutable)
                ordered_pieces: orderedPieces, // Total ordered pieces
                received_pieces: receivedPieces, // Already received pieces
                remaining_pieces: remainingPieces, // Available to receive
                pieces_count: 0, // Start with 0 - user types received pieces (cannot exceed remaining)
                from_po: true, // Flag to mark as from PO (for read-only fields)
              };
            } else {
              // For quantity-based items
              return {
                ...baseItem,
                quantity: 0, // Start with 0 - user types received quantity (cannot exceed remaining)
              };
            }
          });
        setValue('items', poItems);
      }
    } else if (!watchedPoId && !prefillPoId) {
      // Reset to defaults when no PO is selected
      setValue('received_at', new Date().toISOString().split('T')[0]);
      setValue('items', [{ product_id: 0, quantity: 0, unit_cost: 0 }]);
      setValue('vendor_id', undefined);
    }
  }, [currentPoData, watchedPoId, prefillPoId, setValue]);

  const { fields, append, remove } = useFieldArray({
    control,
    name: 'items',
  });

  const watchedItems = watch('items');
  
  // Helper function to get product details
  const getProductInfo = (productId) => {
    if (!productId) return null;
    return products.find(p => p.id === parseInt(productId));
  };

  // Helper function to check if product is dimension-based RM
  const isDimensionBasedRM = (productId) => {
    const product = getProductInfo(productId);
    return product?.product_type === 'RM' && product?.track_by_dimensions === true;
  };

  const calculateTotal = () => {
    return watchedItems?.reduce((sum, item) => {
      const unitCost = parseFloat(item.unit_cost) || 0;
      let itemQuantity = 0;
      
      // For dimension-based RM, use pieces_count; for special items RM, use quantity
      if (isDimensionBasedRM(item.product_id)) {
        itemQuantity = parseFloat(item.pieces_count) || 0;
      } else {
        itemQuantity = parseFloat(item.quantity) || 0;
      }
      
      return sum + itemQuantity * unitCost;
    }, 0) || 0;
  };

  const createGRNMutation = useMutation({
    mutationFn: async (data) => {
      const grnData = {
        ...(data.purchase_order_id && { purchase_order_id: parseInt(data.purchase_order_id) }),
        ...(data.vendor_id && { vendor_id: parseInt(data.vendor_id) }),
        ...(data.received_at && { received_at: data.received_at }),
        items: data.items
          .filter((item) => {
            // Filter items that have valid data (quantity > 0 for special items RM, or pieces_count > 0 for dimension-based RM)
            if (isDimensionBasedRM(item.product_id)) {
              return item.pieces_count > 0;
            } else {
              return item.quantity > 0;
            }
          })
          .map((item) => {
            const productId = parseInt(item.product_id);
            const baseItem = {
              product_id: productId,
              variant_id: item.variant_id ? parseInt(item.variant_id) : undefined,
              unit_cost: parseFloat(item.unit_cost),
            };

            // For dimension-based RM, include dimension fields
            if (isDimensionBasedRM(productId)) {
              return {
                ...baseItem,
                quantity: parseFloat(item.pieces_count || 0), // quantity = pieces_count for dimension-based RM
                piece_length: parseFloat(item.piece_length),
                piece_width: parseFloat(item.piece_width),
                dimension_unit: item.dimension_unit,
                pieces_count: parseInt(item.pieces_count),
              };
            } else {
              // For special items RM and FG, use quantity
              return {
                ...baseItem,
                quantity: parseFloat(item.quantity),
              };
            }
          }),
        notes: data.notes || undefined,
      };
      return await procurementAPI.createGRN(grnData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['grns']);
      toast.success('GRN created successfully!');
      router.push('/procurement/grns');
    },
    onError: (error) => {
      console.error('GRN creation error:', error);
      
      // Extract error message from response
      const errorData = error?.response?.data;
      let errorMessage = 'Failed to create GRN';
      
      if (errorData) {
        // Check for validation error message
        if (errorData.message) {
          errorMessage = errorData.message;
        }
        // Check for errors array (validation errors)
        else if (errorData.errors && Array.isArray(errorData.errors)) {
          const errorMessages = errorData.errors.map(err => 
            err.message || err.msg || err.field || String(err)
          ).join(', ');
          errorMessage = `Validation errors: ${errorMessages}`;
        }
        // Check for error object
        else if (errorData.error) {
          errorMessage = errorData.error;
        }
      } else if (error.message) {
        errorMessage = error.message;
      }
      
      // Show user-friendly error message with better styling
      toast.error(errorMessage, {
        duration: 6000, // Show for 6 seconds (longer for important errors)
        position: 'top-center',
        style: {
          background: '#ef4444',
          color: '#fff',
          padding: '16px 20px',
          borderRadius: '8px',
          fontSize: '15px',
          fontWeight: '500',
          maxWidth: '600px',
          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
          border: '1px solid #dc2626',
        },
        iconTheme: {
          primary: '#fff',
          secondary: '#ef4444',
        },
      });
      
      // Log full error for debugging
      console.error('Full error details:', {
        message: errorMessage,
        response: error?.response,
        data: errorData,
      });
    },
  });

  const onSubmit = async (data) => {
    console.log('Form submitted with data:', data);
    console.log('Form errors:', errors);
    setIsSubmitting(true);
    try {
      await createGRNMutation.mutateAsync(data);
    } catch (error) {
      console.error('Error in onSubmit:', error);
      // Error handled in mutation
    } finally {
      setIsSubmitting(false);
    }
  };

  const onError = (errors) => {
    console.error('Form validation errors:', errors);
    toast.error('Please fix the form errors before submitting');
  };

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-950 space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button
          variant="outline"
          onClick={() => router.push('/procurement/grns')}
          className="flex items-center gap-2"
        >
          <ArrowLeft className="w-4 h-4" />
          Back
        </Button>
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">New GRN</h1>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Create a new Goods Received Note
          </p>
        </div>
      </div>

      {/* Form */}
      <Card>
        <CardHeader>
          <CardTitle>GRN Information</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit, onError)} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Purchase Order (Optional)
                </label>
                <select
                  {...register('purchase_order_id', { valueAsNumber: true })}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:text-white"
                  defaultValue={prefillPoId ? parseInt(prefillPoId) : ''}
                  disabled={!!prefillPoId}
                  onChange={(e) => {
                    const value = e.target.value ? parseInt(e.target.value) : undefined;
                    setValue('purchase_order_id', value);
                  }}
                >
                  <option value="">Select purchase order...</option>
                  {purchaseOrders
                    .filter((po) => po.status === 'CONFIRMED' || po.status === 'DRAFT')
                    .map((po) => (
                      <option key={po.id} value={po.id}>
                        {po.po_number || `PO-${po.id}`} {po.status === 'CONFIRMED' ? '(Confirmed)' : '(Draft)'}
                      </option>
                    ))}
                </select>
                {(prefillPoId || watchedPoId) && currentPoData && (
                  <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                    ✓ Vendor and received date auto-filled.{' '}
                    {currentPoData.items && currentPoData.items.length > 0
                      ? `${currentPoData.items.length} item(s) loaded. Type quantities received below (unit costs from PO).`
                      : 'Note: PO items not available. Items can be added manually below.'}
                  </p>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Vendor (Optional)
                </label>
                <select
                  {...register('vendor_id', { valueAsNumber: true })}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:text-white"
                >
                  <option value="">Select vendor...</option>
                  {vendors.map((vendor) => (
                    <option key={vendor.id} value={vendor.id}>
                      {vendor.name}
                    </option>
                  ))}
                </select>
              </div>

              <Input
                label="Received Date"
                type="date"
                {...register('received_at')}
                error={errors.received_at?.message}
                defaultValue={new Date().toISOString().split('T')[0]}
                required
              />
            </div>

            {/* Items Section */}
            <div className="border-t dark:border-gray-700 pt-6">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Items</h3>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => append({ product_id: 0, quantity: 0, unit_cost: 0 })}
                  className="flex items-center gap-2"
                >
                  <Plus className="w-4 h-4" />
                  Add Item
                </Button>
              </div>

              {fields.map((field, index) => {
                const itemProductId = watchedItems?.[index]?.product_id;
                const isDimBased = isDimensionBasedRM(itemProductId);
                
                return (
                <div key={field.id} className="space-y-4 mb-4 p-4 border dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800">
                  {/* First row: Product, Quantity/Dimensions, Unit Cost, Total, Delete */}
                  <div className="grid grid-cols-12 gap-4">
                    <div className="col-span-5">
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        Product <span className="text-red-500">*</span>
                      </label>
                      <select
                        {...register(`items.${index}.product_id`, { valueAsNumber: true })}
                        className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-900 dark:text-white dark:border-gray-600 ${
                          errors.items?.[index]?.product_id ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
                        }`}
                        required
                      >
                        <option value="">Select product...</option>
                        {products.map((product) => (
                          <option key={product.id} value={product.id}>
                            {product.name}
                          </option>
                        ))}
                      </select>
                      {errors.items?.[index]?.product_id && (
                        <p className="mt-1 text-sm text-red-600">
                          {errors.items[index].product_id.message}
                        </p>
                      )}
                    </div>

                    {/* Conditional fields based on product type */}
                    {isDimBased ? (
                      // Dimension-based RM - show label only on first row
                      <div className="col-span-2">
                        <div className="text-xs font-medium text-blue-600 dark:text-blue-400 mb-1">
                          Dimension-Based RM
                        </div>
                      </div>
                    ) : (
                      // Quantity field for special items RM and FG
                      <div className="col-span-2">
                      <Input
                        label={
                          watchedItems?.[index]?.remaining_quantity !== undefined
                            ? `Received Qty (Remaining: ${watchedItems[index].remaining_quantity})`
                            : watchedItems?.[index]?.ordered_quantity
                            ? `Received Qty (Ordered: ${watchedItems[index].ordered_quantity})`
                            : 'Quantity Received'
                        }
                        type="number"
                        step="0.01"
                        min="0"
                        max={watchedItems?.[index]?.remaining_quantity !== undefined ? watchedItems[index].remaining_quantity : undefined}
                        {...register(`items.${index}.quantity`, { 
                          valueAsNumber: true,
                          validate: (value) => {
                            const remaining = watchedItems?.[index]?.remaining_quantity;
                            if (remaining !== undefined && parseFloat(value) > remaining) {
                              return `Cannot receive more than ${remaining} (remaining quantity)`;
                            }
                            return true;
                          }
                        })}
                        error={errors.items?.[index]?.quantity?.message}
                        required
                        placeholder="0"
                      />
                      {watchedItems?.[index]?.ordered_quantity && (
                        <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                          Ordered: {watchedItems[index].ordered_quantity}
                          {watchedItems[index]?.received_quantity > 0 && (
                            <span className="text-gray-600 dark:text-gray-300 ml-1">
                              • Already received: {watchedItems[index].received_quantity}
                            </span>
                          )}
                          {watchedItems[index]?.remaining_quantity !== undefined && (
                            <span className="text-blue-600 dark:text-blue-400 ml-1">
                              • Remaining: {watchedItems[index].remaining_quantity}
                            </span>
                          )}
                          {parseFloat(watchedItems[index]?.quantity || 0) > parseFloat(watchedItems[index]?.remaining_quantity || 0) && (
                            <span className="text-red-600 dark:text-red-400 ml-1 block">⚠ Cannot exceed remaining quantity</span>
                          )}
                          {parseFloat(watchedItems[index]?.quantity || 0) > 0 && 
                           parseFloat(watchedItems[index]?.quantity || 0) < parseFloat(watchedItems[index]?.remaining_quantity || 0) && (
                            <span className="text-orange-600 dark:text-orange-400 ml-1 block">⚠ Partial receiving</span>
                          )}
                        </p>
                      )}
                      </div>
                    )}

                    {/* Unit Cost */}
                    <div className="col-span-2">
                      <Input
                        label="Unit Cost"
                        type="number"
                        step="0.01"
                        min="0"
                        {...register(`items.${index}.unit_cost`, { valueAsNumber: true })}
                        error={errors.items?.[index]?.unit_cost?.message}
                        required
                        readOnly={!!currentPoData?.items?.[index]} // Read-only if from PO
                        className={currentPoData?.items?.[index] ? 'bg-gray-100 dark:bg-gray-700 cursor-not-allowed' : ''}
                      />
                    </div>

                    {/* Total */}
                    <div className="col-span-2 flex items-end">
                      <div className="w-full">
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Total</label>
                        <div className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-white">
                          {formatCurrency(
                            (isDimBased
                              ? (parseFloat(watchedItems?.[index]?.pieces_count) || 0)
                              : (parseFloat(watchedItems?.[index]?.quantity) || 0)
                            ) * (parseFloat(watchedItems?.[index]?.unit_cost) || 0)
                          )}
                        </div>
                      </div>
                    </div>

                    {/* Delete Button */}
                    <div className="col-span-1 flex items-end">
                      {fields.length > 1 && (
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          onClick={() => remove(index)}
                          className="text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      )}
                    </div>
                  </div>

                  {/* Second row: Dimension fields for dimension-based RM */}
                  {isDimBased && (
                    <div className="grid grid-cols-12 gap-4 mt-4">
                      <div className="col-span-12 space-y-3">
                        <div className="text-xs font-medium text-blue-600 dark:text-blue-400 mb-2">
                          Piece Dimensions
                        </div>
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                          {/* Display dimensions as text when from PO, otherwise show inputs */}
                          {watchedItems?.[index]?.from_po ? (
                            <>
                              <div>
                                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                  Length
                                </label>
                                <p className="px-3 py-2 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg text-gray-900 dark:text-white font-medium">
                                  {watchedItems[index].piece_length || '0.00'} {watchedItems[index].dimension_unit || ''}
                                </p>
                                <input
                                  type="hidden"
                                  {...register(`items.${index}.piece_length`, { 
                                    valueAsNumber: true,
                                    value: watchedItems[index]?.piece_length || 0
                                  })}
                                />
                              </div>
                              <div>
                                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                  Width
                                </label>
                                <p className="px-3 py-2 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg text-gray-900 dark:text-white font-medium">
                                  {watchedItems[index].piece_width || '0.00'} {watchedItems[index].dimension_unit || ''}
                                </p>
                                <input
                                  type="hidden"
                                  {...register(`items.${index}.piece_width`, { 
                                    valueAsNumber: true,
                                    value: watchedItems[index]?.piece_width || 0
                                  })}
                                />
                              </div>
                              <div>
                                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                  Unit
                                </label>
                                <p className="px-3 py-2 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg text-gray-900 dark:text-white font-medium uppercase">
                                  {watchedItems[index].dimension_unit || 'N/A'}
                                </p>
                                <input
                                  type="hidden"
                                  {...register(`items.${index}.dimension_unit`, {
                                    value: watchedItems[index]?.dimension_unit || ''
                                  })}
                                />
                              </div>
                              <div>
                                <Input
                                  label={
                                    watchedItems?.[index]?.remaining_pieces !== undefined
                                      ? `Received Pieces (Remaining: ${watchedItems[index].remaining_pieces})`
                                      : watchedItems?.[index]?.ordered_pieces
                                      ? `Received Pieces (Ordered: ${watchedItems[index].ordered_pieces})`
                                      : 'Pieces Received'
                                  }
                                  type="number"
                                  step="1"
                                  min="0"
                                  max={watchedItems?.[index]?.remaining_pieces !== undefined ? watchedItems[index].remaining_pieces : undefined}
                                  {...register(`items.${index}.pieces_count`, { 
                                    valueAsNumber: true,
                                    validate: (value) => {
                                      const remaining = watchedItems?.[index]?.remaining_pieces;
                                      if (remaining !== undefined && parseFloat(value) > remaining) {
                                        return `Cannot receive more than ${remaining} pieces (remaining)`;
                                      }
                                      return true;
                                    }
                                  })}
                                  error={errors.items?.[index]?.pieces_count?.message}
                                  placeholder="0"
                                  required
                                />
                                {watchedItems?.[index]?.ordered_pieces && (
                                  <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    Ordered: {watchedItems[index].ordered_pieces}
                                    {watchedItems[index]?.received_pieces > 0 && (
                                      <span className="text-gray-600 dark:text-gray-300 ml-1">
                                        • Already received: {watchedItems[index].received_pieces}
                                      </span>
                                    )}
                                    {watchedItems[index]?.remaining_pieces !== undefined && (
                                      <span className="text-blue-600 dark:text-blue-400 ml-1">
                                        • Remaining: {watchedItems[index].remaining_pieces}
                                      </span>
                                    )}
                                  </p>
                                )}
                              </div>
                            </>
                          ) : (
                            <>
                              <div>
                                <Input
                                  label="Length"
                                  type="number"
                                  step="0.01"
                                  min="0"
                                  {...register(`items.${index}.piece_length`, { valueAsNumber: true })}
                                  error={errors.items?.[index]?.piece_length?.message}
                                  placeholder="0.00"
                                  required
                                />
                              </div>
                              <div>
                                <Input
                                  label="Width"
                                  type="number"
                                  step="0.01"
                                  min="0"
                                  {...register(`items.${index}.piece_width`, { valueAsNumber: true })}
                                  error={errors.items?.[index]?.piece_width?.message}
                                  placeholder="0.00"
                                  required
                                />
                              </div>
                              <div>
                                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                  Unit
                                </label>
                                <select
                                  {...register(`items.${index}.dimension_unit`)}
                                  className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-900 dark:text-white dark:border-gray-600 ${
                                    errors.items?.[index]?.dimension_unit ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
                                  }`}
                                  required
                                >
                                  <option value="">Select</option>
                                  <option value="inch">Inch</option>
                                  <option value="cm">cm</option>
                                  <option value="m">m</option>
                                </select>
                                {errors.items?.[index]?.dimension_unit && (
                                  <p className="mt-1 text-sm text-red-600">{errors.items[index].dimension_unit.message}</p>
                                )}
                              </div>
                              <div>
                                <Input
                                  label="Pieces Received"
                                  type="number"
                                  step="1"
                                  min="0"
                                  {...register(`items.${index}.pieces_count`, { valueAsNumber: true })}
                                  error={errors.items?.[index]?.pieces_count?.message}
                                  placeholder="0"
                                  required
                                />
                              </div>
                            </>
                          )}
                        </div>
                        {watchedItems?.[index]?.piece_length && watchedItems?.[index]?.piece_width && (
                          <p className="text-xs text-gray-500 dark:text-gray-400">
                            Total area: {(parseFloat(watchedItems[index].piece_length) * parseFloat(watchedItems[index].piece_width) * (parseFloat(watchedItems[index].pieces_count) || 0)).toFixed(2)} {watchedItems[index].dimension_unit || ''}²
                          </p>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              );
              })}

              <div className="mt-4 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg flex justify-end">
                <div className="text-right">
                  <p className="text-sm text-gray-600 dark:text-gray-400">Total Amount:</p>
                  <p className="text-2xl font-bold text-gray-900 dark:text-white">{formatCurrency(calculateTotal())}</p>
                </div>
              </div>
            </div>

            <div className="flex justify-end gap-4 pt-4 border-t dark:border-gray-700">
              <Button
                type="button"
                variant="outline"
                onClick={() => router.push('/procurement/grns')}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button type="submit" variant="primary" disabled={isSubmitting} loading={isSubmitting}>
                Create GRN
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}


