/**
 * Production Order Detail Page
 * View production order details and manage production
 */

'use client';

import { useParams, useRouter } from 'next/navigation';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { productionAPI } from '@/lib/api/production';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  Badge,
  LoadingPage,
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHead,
  TableCell,
  Modal,
  Input,
} from '@/components/ui';
import { formatDate, formatDateTime } from '@/lib/utils/format';
import { ArrowLeft, CheckCircle, AlertTriangle, Printer } from 'lucide-react';
import toast from 'react-hot-toast';
import { useState } from 'react';

export default function ProductionOrderDetailPage() {
  const router = useRouter();
  const params = useParams();
  const orderId = parseInt(params.id);
  const queryClient = useQueryClient();
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [showAvailabilityModal, setShowAvailabilityModal] = useState(false);
  const [availabilityData, setAvailabilityData] = useState(null);
  const [confirmQuantity, setConfirmQuantity] = useState(null);
  const [printLabelsAfterConfirm, setPrintLabelsAfterConfirm] = useState(true);

  // Fetch production order details
  const { data: order, isLoading, error, refetch } = useQuery({
    queryKey: ['production-order', orderId],
    queryFn: async () => {
      if (isNaN(orderId)) {
        throw new Error('Invalid production order ID');
      }
      const response = await productionAPI.getProductionOrder(orderId);
      return response?.data || response;
    },
    enabled: !isNaN(orderId),
  });

  // Check availability
  const checkAvailabilityMutation = useMutation({
    mutationFn: async () => {
      const response = await productionAPI.checkAvailability(orderId);
      return response?.data || response;
    },
    onSuccess: (data) => {
      setAvailabilityData(data);
      setShowAvailabilityModal(true);
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to check availability';
      toast.error(message);
    },
  });

  const confirmProductionMutation = useMutation({
    mutationFn: async ({ generateUIDs = true, confirmQuantity = null }) => {
      return await productionAPI.confirmProduction(orderId, { generateUIDs, confirmQuantity });
    },
    onSuccess: (response) => {
      queryClient.invalidateQueries(['production-order', orderId]);
      queryClient.invalidateQueries(['production-orders']);
      queryClient.invalidateQueries(['inventory']);
      const message = response?.data?.message || response?.message || 'Production confirmed! Raw materials consumed and finished goods created.';
      toast.success(message);
      setShowConfirmModal(false);
      setConfirmQuantity(null);
      refetch();
      // Redirect to reprint labels page if option is enabled
      if (printLabelsAfterConfirm) {
        router.push(`/label-printing/reprint?source=PRODUCTION&reference_id=${orderId}`);
      }
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to confirm production';
      toast.error(message);
      setShowConfirmModal(false);
    },
  });

  const handleCheckAvailability = () => {
    checkAvailabilityMutation.mutate();
  };

  const handleConfirmProduction = (generateUIDs = true) => {
    // Only include confirmQuantity in payload if it's explicitly set (not null)
    // If null, backend will default to remaining quantity
    const payload = { generateUIDs };
    if (confirmQuantity !== null && confirmQuantity !== undefined) {
      payload.confirmQuantity = confirmQuantity;
    }
    confirmProductionMutation.mutate(payload);
  };

  if (isLoading) {
    return <LoadingPage message="Loading production order details..." />;
  }

  if (error) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-red-600">
        <p>Error: {error.message}</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  if (!order) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-gray-600">
        <p>Production order not found.</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  const isFullyConfirmed = order.status === 'CONFIRMED';
  const isPartiallyConfirmed = order.status === 'PARTIALLY_CONFIRMED';
  // Only allow confirmation actions when order is in PLANNED/DRAFT or partially confirmed state
  const canConfirmMore =
    order.status === 'PLANNED' ||
    order.status === 'DRAFT' ||
    isPartiallyConfirmed;

  // Remaining quantity logic:
  // - For partially confirmed: use backend remaining_quantity (fallback to quantity - confirmed)
  // - For planned/draft: allow confirming up to the full order quantity
  const baseRemaining =
    Number(order.quantity || 0) - Number(order.confirmed_quantity || 0);
  const remainingQuantity = isPartiallyConfirmed
    ? Math.max(
        0,
        Math.floor(
          order.remaining_quantity != null
            ? order.remaining_quantity
            : baseRemaining
        )
      )
    : Math.max(0, Math.floor(order.quantity || 0));

  return (
    <div className="container mx-auto p-6">
      <div className="flex justify-between items-center mb-6">
        <Button variant="ghost" onClick={() => router.back()} className="flex items-center">
          <ArrowLeft className="w-4 h-4 mr-2" /> Back to Production Orders
        </Button>
        <div className="flex gap-2">
          {canConfirmMore && (
            <>
              <Button
                variant="outline"
                onClick={handleCheckAvailability}
                disabled={checkAvailabilityMutation.isLoading}
                loading={checkAvailabilityMutation.isLoading}
                className="flex items-center gap-2"
              >
                <AlertTriangle className="w-4 h-4" />
                Check Availability
              </Button>
              <Button
                variant="primary"
                onClick={() => {
                  // Pre-fill confirmQuantity with remaining quantity when modal opens
                  const baseRemaining =
                    Number(order.quantity || 0) - Number(order.confirmed_quantity || 0);
                  const calculatedRemaining = isPartiallyConfirmed
                    ? Math.max(
                        0,
                        Math.floor(
                          order.remaining_quantity != null
                            ? order.remaining_quantity
                            : baseRemaining
                        )
                      )
                    : Math.max(0, Math.floor(order.quantity || 0));
                  setConfirmQuantity(calculatedRemaining > 0 ? calculatedRemaining : null);
                  setShowConfirmModal(true);
                }}
                disabled={confirmProductionMutation.isLoading}
                loading={confirmProductionMutation.isLoading}
                className="flex items-center gap-2"
              >
                <CheckCircle className="w-4 h-4" />
                Confirm Production
              </Button>
            </>
          )}
          {isFullyConfirmed && (
            <Button
              variant="outline"
              onClick={() => router.push(`/label-printing/reprint?source=PRODUCTION&reference_id=${orderId}`)}
              className="flex items-center gap-2"
            >
              <Printer className="w-4 h-4" />
              Reprint Labels
            </Button>
          )}
        </div>
      </div>

      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <span>Production Order #PO-{order.id}</span>
            <Badge variant={isFullyConfirmed ? 'success' : isPartiallyConfirmed ? 'warning' : 'default'}>
              {order.status === 'PARTIALLY_CONFIRMED' ? 'PARTIALLY CONFIRMED' : order.status}
            </Badge>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <h3 className="font-semibold text-gray-700 mb-3">Production Information</h3>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Finished Good:</span>{' '}
                {order.finishedGoodVariant?.product?.name || 'Unknown Product'}
              </p>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Variant:</span>{' '}
                {order.finishedGoodVariant?.name || 'Default'}
              </p>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Order Quantity:</span>{' '}
                <strong className="text-lg">{Math.floor(order.quantity)}</strong>
              </p>
              {order.confirmed_quantity !== undefined && order.confirmed_quantity !== null && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Confirmed:</span>{' '}
                  <strong className="text-lg text-green-600">{Math.floor(order.confirmed_quantity)}</strong>
                </p>
              )}
              {(order.remaining_quantity !== undefined && order.remaining_quantity !== null && order.remaining_quantity > 0) && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Remaining:</span>{' '}
                  <strong className="text-lg text-orange-600">{Math.floor(order.remaining_quantity)}</strong>
                </p>
              )}
            </div>
            <div>
              <h3 className="font-semibold text-gray-700 mb-3">Status</h3>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Created:</span> {formatDateTime(order.created_at)}
              </p>
              {order.confirmed_at && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Confirmed:</span> {formatDateTime(order.confirmed_at)}
                </p>
              )}
            </div>
          </div>
        </CardContent>
      </Card>

      {order.bom && order.bom.items && order.bom.items.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Required Raw Materials (from BOM)</CardTitle>
          </CardHeader>
          <CardContent>
            {availabilityData && !availabilityData.all_available && availabilityData.max_producible_units !== null && (
              <div className="mb-4 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
                <div className="flex items-start gap-3">
                  <div className="flex-1">
                    <p className="text-sm font-medium text-blue-800 dark:text-blue-200">
                      ⚠️ Limited Material Availability
                    </p>
                    <p className="text-sm text-blue-700 dark:text-blue-300 mt-1">
                      You can produce <strong>{availabilityData.max_producible_units}</strong> units with available materials 
                      (requested: {availabilityData.requested_quantity} units).
                    </p>
                    {availabilityData.max_producible_units > 0 && (
                      <p className="text-xs text-blue-600 dark:text-blue-400 mt-1">
                        Consider reducing the production quantity or adding more raw materials to meet the full requirement.
                      </p>
                    )}
                  </div>
                </div>
              </div>
            )}
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Raw Material</TableHead>
                  <TableHead>Type</TableHead>
                  <TableHead>Requirements</TableHead>
                  {availabilityData && (
                    <>
                      <TableHead align="right">Available</TableHead>
                      <TableHead>Status</TableHead>
                    </>
                  )}
                </TableRow>
              </TableHeader>
              <TableBody>
                {order.bom.items.map((item, idx) => {
                  const isDimensionBased = item.use_dimensions === true;
                  const product = item.rawMaterial;
                  
                  // Get availability data for this item
                  const itemAvailability = availabilityData?.items?.[idx];
                  
                  // Calculate required total based on item type
                  let requiredTotal, requiredDisplay, available, shortfall, maxProducible;
                  if (isDimensionBased) {
                    // For dimension-based, show dimension requirements and total area needed
                    const areaPerUnit = parseFloat(item.required_length || 0) * parseFloat(item.required_width || 0);
                    requiredTotal = areaPerUnit * parseFloat(order.quantity);
                    requiredDisplay = `${parseFloat(order.quantity)} × (${item.required_length} × ${item.required_width} ${item.dimension_unit || 'm'})`;
                    available = itemAvailability?.available_area || 0;
                    shortfall = itemAvailability?.shortfall || 0;
                    maxProducible = itemAvailability?.max_producible_units || 0;
                  } else {
                    // For quantity-based
                    requiredTotal = parseFloat(order.quantity) * parseFloat(item.quantity_per_unit);
                    requiredDisplay = `${item.quantity_per_unit} per unit`;
                    available = itemAvailability?.current_quantity || 0;
                    shortfall = itemAvailability?.shortfall || 0;
                    maxProducible = itemAvailability?.max_producible_units || 0;
                  }
                  
                  const sufficient = itemAvailability?.available === true;

                  return (
                    <TableRow key={item.id}>
                      <TableCell className="font-medium">
                        {product?.name || 'Unknown'}
                      </TableCell>
                      <TableCell>
                        {isDimensionBased ? (
                          <Badge variant="info">Dimension-Based</Badge>
                        ) : (
                          <Badge variant="secondary">Quantity-Based</Badge>
                        )}
                      </TableCell>
                      <TableCell>
                        <div>
                          <div className="font-medium">
                            {isDimensionBased ? (
                              <span>{item.required_length} × {item.required_width} {item.dimension_unit || 'm'} per unit</span>
                            ) : (
                              <span>{item.quantity_per_unit} {product?.unit_of_measure ? product.unit_of_measure : 'units'} per unit</span>
                            )}
                          </div>
                          <div className="text-xs text-gray-500 mt-1">
                            Total required: {isDimensionBased 
                              ? `${requiredTotal.toFixed(2)} ${item.dimension_unit || 'm'}²`
                              : `${requiredTotal.toFixed(3)} ${product?.unit_of_measure ? product.unit_of_measure : 'units'}`}
                          </div>
                        </div>
                      </TableCell>
                      {availabilityData && (
                        <>
                          <TableCell align="right">
                            <div className="space-y-1">
                              <div>
                                <span className={sufficient ? 'text-green-600 font-medium' : 'text-red-600 font-medium'}>
                                  {isDimensionBased 
                                    ? `${available.toFixed(2)} ${item.dimension_unit || 'm'}²`
                                    : `${available.toFixed(3)} ${product?.unit_of_measure ? product.unit_of_measure : 'units'}`}
                                </span>
                                <span className="text-gray-500 text-xs ml-2">
                                  (Required: {isDimensionBased 
                                    ? `${itemAvailability?.total_area_required?.toFixed(2) || requiredTotal.toFixed(2)} ${item.dimension_unit || 'm'}²`
                                    : `${itemAvailability?.required_quantity?.toFixed(3) || requiredTotal.toFixed(3)} ${product?.unit_of_measure ? product.unit_of_measure : 'units'}`})
                                </span>
                              </div>
                              {shortfall > 0 && (
                                <div className="text-xs text-red-600">
                                  Shortfall: {isDimensionBased 
                                    ? `${shortfall.toFixed(2)} ${item.dimension_unit || 'm'}²`
                                    : `${shortfall.toFixed(3)} ${product?.unit_of_measure ? product.unit_of_measure : 'units'}`}
                                </div>
                              )}
                              {maxProducible > 0 && maxProducible < order.quantity && (
                                <div className="text-xs text-blue-600 font-medium">
                                  Max producible: {maxProducible} units
                                </div>
                              )}
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="space-y-1">
                              <Badge variant={sufficient ? 'success' : 'error'}>
                                {sufficient ? 'Available' : 'Insufficient'}
                              </Badge>
                              {maxProducible > 0 && maxProducible < order.quantity && (
                                <div className="text-xs text-blue-600 mt-1">
                                  Can produce {maxProducible} of {order.quantity}
                                </div>
                              )}
                            </div>
                          </TableCell>
                        </>
                      )}
                      {!availabilityData && (
                        <TableCell colSpan={2} className="text-sm text-gray-500">
                          Click "Check Availability" to see stock levels
                        </TableCell>
                      )}
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
            {!availabilityData && (
              <div className="mt-4 flex justify-end">
                <Button
                  variant="outline"
                  onClick={handleCheckAvailability}
                  disabled={checkAvailabilityMutation.isLoading}
                  loading={checkAvailabilityMutation.isLoading}
                  className="flex items-center gap-2"
                >
                  <AlertTriangle className="w-4 h-4" />
                  Check Availability
                </Button>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {(!order.bom || !order.bom.items || order.bom.items.length === 0) && (
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-8 text-gray-500">
              <AlertTriangle className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p className="font-medium mb-2">No BOM found for this finished good variant</p>
              <p className="text-sm mb-4">
                A BOM (Bill of Materials) must be created before production can be confirmed.
              </p>
              <Button
                variant="outline"
                onClick={() => router.push('/production/boms/new')}
              >
                Create BOM
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Confirm Production Modal */}
      <Modal
        isOpen={showConfirmModal}
        onClose={() => {
          setShowConfirmModal(false);
          // Reset to null when closing, will be re-initialized when opening
          setConfirmQuantity(null);
        }}
        title={isPartiallyConfirmed ? "Confirm Additional Production" : "Confirm Production"}
        description={isPartiallyConfirmed 
          ? `Continue production for remaining ${remainingQuantity} unit${remainingQuantity !== 1 ? 's' : ''}. This will consume raw materials and create finished goods.`
          : "This will consume raw materials and create finished goods. This action cannot be undone."
        }
      >
        <div className="space-y-4 mt-4">
          {isPartiallyConfirmed && (
            <div className="bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
              <p className="text-sm font-medium text-blue-900 dark:text-blue-100 mb-2">
                Partial Production Status
              </p>
              <div className="text-sm text-blue-800 dark:text-blue-200 space-y-1">
                <p>Total Order: {Math.floor(order.quantity)} units</p>
                <p>Already Confirmed: {Math.floor(order.confirmed_quantity || 0)} units</p>
                <p className="font-semibold">Remaining: {Math.floor(remainingQuantity)} units</p>
              </div>
            </div>
          )}
          
          <div className="space-y-2">
            <label htmlFor="confirmQuantity" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
              Quantity to Confirm {remainingQuantity > 0 && `(Max: ${Math.floor(remainingQuantity)})`}
            </label>
            <Input
              id="confirmQuantity"
              type="number"
              step="1"
              min="1"
              max={remainingQuantity > 0 ? Math.floor(remainingQuantity) : undefined}
              value={
                confirmQuantity !== null && confirmQuantity !== undefined
                  ? Math.floor(confirmQuantity)
                  : remainingQuantity > 0
                    ? Math.floor(remainingQuantity)
                    : ''
              }
              onChange={(e) => {
                const value = parseInt(e.target.value, 10);
                const maxQty = Math.floor(remainingQuantity);
                if (!isNaN(value) && value > 0 && (isNaN(maxQty) || maxQty <= 0 || value <= maxQty)) {
                  setConfirmQuantity(value);
                } else if (e.target.value === '') {
                  setConfirmQuantity(null);
                } else if (!isNaN(value) && !isNaN(maxQty) && maxQty > 0 && value > maxQty) {
                  setConfirmQuantity(maxQty);
                }
              }}
              placeholder={`Enter quantity (max: ${Math.floor(remainingQuantity)})`}
              className="w-full"
            />
            <p className="text-xs text-gray-500">
              {remainingQuantity <= 0
                ? 'No remaining quantity to confirm.'
                : confirmQuantity !== null
                  ? `You are confirming ${confirmQuantity} unit${confirmQuantity !== 1 ? 's' : ''}${
                      isPartiallyConfirmed
                        ? ` (${Math.max(0, Math.floor(remainingQuantity - confirmQuantity))} will remain)`
                        : ''
                    }`
                  : `Leave empty to confirm all ${Math.floor(remainingQuantity)} unit${
                      Math.floor(remainingQuantity) !== 1 ? 's' : ''
                    }`
              }
            </p>
          </div>
          
          <p className="text-sm text-gray-600 mt-4">
            This will:
          </p>
          <ul className="list-disc list-inside text-sm text-gray-600 ml-4">
            <li>Consume raw materials from inventory for {confirmQuantity !== null ? confirmQuantity : Math.floor(remainingQuantity)} unit{(confirmQuantity !== null ? confirmQuantity : Math.floor(remainingQuantity)) !== 1 ? 's' : ''}</li>
            <li>Create finished goods in inventory</li>
            <li>Generate UIDs if the product tracks inventory by UID</li>
            <li>{isPartiallyConfirmed 
              ? `Update production order (${Math.floor((order.confirmed_quantity || 0) + (confirmQuantity !== null ? confirmQuantity : Math.floor(remainingQuantity)))}/${Math.floor(order.quantity)} confirmed)`
              : `Update production order status to ${confirmQuantity !== null && confirmQuantity < Math.floor(remainingQuantity) ? 'PARTIALLY_CONFIRMED' : 'CONFIRMED'}`
            }</li>
          </ul>
          
          <div className="flex items-center gap-3 p-4 bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-lg mt-4">
            <input
              type="checkbox"
              id="print-labels-production"
              checked={printLabelsAfterConfirm}
              onChange={(e) => setPrintLabelsAfterConfirm(e.target.checked)}
              className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700"
            />
            <label htmlFor="print-labels-production" className="text-sm font-medium text-gray-700 dark:text-gray-300 cursor-pointer">
              Print labels for FG items after confirmation
            </label>
          </div>
          <p className="text-xs text-gray-500 dark:text-gray-400">
            If enabled, you'll be redirected to the label printing page to print labels for all finished goods items created from this production order.
          </p>
        </div>
        <div className="flex justify-end gap-4 mt-6">
          <Button variant="outline" onClick={() => {
            setShowConfirmModal(false);
            setConfirmQuantity(null);
          }}>
            Cancel
          </Button>
          <Button
            variant="primary"
            onClick={() => handleConfirmProduction(true)}
            disabled={confirmProductionMutation.isLoading || (confirmQuantity !== null && (confirmQuantity <= 0 || confirmQuantity > remainingQuantity))}
            loading={confirmProductionMutation.isLoading}
          >
            {isPartiallyConfirmed ? 'Confirm Additional Production' : 'Confirm Production'}
          </Button>
        </div>
      </Modal>

      {/* Availability Modal */}
      <Modal
        isOpen={showAvailabilityModal}
        onClose={() => setShowAvailabilityModal(false)}
        title="Raw Material Availability"
        description="Check if sufficient raw materials are available for production"
      >
        {availabilityData && (
          <div className="mt-4 space-y-4">
            {/* Overall Status */}
            <div className={availabilityData.all_available 
              ? "p-4 bg-green-50 dark:bg-green-900/20 rounded-lg border border-green-200 dark:border-green-800"
              : "p-4 bg-red-50 dark:bg-red-900/20 rounded-lg border border-red-200 dark:border-red-800"
            }>
              <div className="flex items-center justify-between">
                <div>
                  <p className={`font-medium ${availabilityData.all_available ? 'text-green-800 dark:text-green-200' : 'text-red-800 dark:text-red-200'}`}>
                    {availabilityData.all_available ? '✓ Sufficient raw materials available' : '✗ Insufficient raw materials'}
                  </p>
                  {availabilityData.requested_quantity && (
                    <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                      Requested: {availabilityData.requested_quantity} units
                    </p>
                  )}
                </div>
                {availabilityData.max_producible_units !== null && availabilityData.max_producible_units < availabilityData.requested_quantity && (
                  <div className="text-right">
                    <p className="text-sm font-medium text-blue-600 dark:text-blue-400">
                      Max Producible: {availabilityData.max_producible_units} units
                    </p>
                    <p className="text-xs text-gray-600 dark:text-gray-400 mt-1">
                      Limited by available materials
                    </p>
                  </div>
                )}
              </div>
            </div>

            {/* Detailed Items Table */}
            {availabilityData.items && availabilityData.items.length > 0 && (
              <div>
                <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Material Details:</h4>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Raw Material</TableHead>
                      <TableHead>Type</TableHead>
                      <TableHead align="right">Required</TableHead>
                      <TableHead align="right">Available</TableHead>
                      <TableHead align="right">Shortfall</TableHead>
                      <TableHead align="right">Max Producible</TableHead>
                      <TableHead>Status</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {availabilityData.items.map((item, idx) => {
                      const isDimBased = item.use_dimensions === true;
                      const required = isDimBased 
                        ? item.total_area_required 
                        : item.required_quantity;
                      const available = isDimBased 
                        ? item.available_area 
                        : item.current_quantity;
                      const shortfall = item.shortfall || 0;
                      const maxProducible = item.max_producible_units || 0;
                      const sufficient = item.available === true;
                      const unit = isDimBased 
                        ? item.dimensions?.unit || 'm' 
                        : 'units';

                      return (
                        <TableRow key={idx}>
                          <TableCell className="font-medium">
                            {item.rm_product_name || 'Unknown'}
                          </TableCell>
                          <TableCell>
                            {isDimBased ? (
                              <Badge variant="info">Dimension-Based</Badge>
                            ) : (
                              <Badge variant="secondary">Quantity-Based</Badge>
                            )}
                          </TableCell>
                          <TableCell align="right">
                            {isDimBased 
                              ? `${parseFloat(required || 0).toFixed(2)} ${unit}²`
                              : `${parseFloat(required || 0).toFixed(3)} ${unit}`}
                          </TableCell>
                          <TableCell align="right">
                            <span className={sufficient ? 'text-green-600 font-medium' : 'text-red-600 font-medium'}>
                              {isDimBased 
                                ? `${parseFloat(available || 0).toFixed(2)} ${unit}²`
                                : `${parseFloat(available || 0).toFixed(3)} ${unit}`}
                            </span>
                          </TableCell>
                          <TableCell align="right">
                            {shortfall > 0 ? (
                              <span className="text-red-600 font-medium">
                                {isDimBased 
                                  ? `${parseFloat(shortfall).toFixed(2)} ${unit}²`
                                  : `${parseFloat(shortfall).toFixed(3)} ${unit}`}
                              </span>
                            ) : (
                              <span className="text-gray-400">-</span>
                            )}
                          </TableCell>
                          <TableCell align="right">
                            {maxProducible > 0 ? (
                              <span className="text-blue-600 font-medium">
                                {maxProducible} units
                              </span>
                            ) : (
                              <span className="text-gray-400">0</span>
                            )}
                          </TableCell>
                          <TableCell>
                            <Badge variant={sufficient ? 'success' : 'error'}>
                              {sufficient ? 'Available' : 'Insufficient'}
                            </Badge>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              </div>
            )}
          </div>
        )}
        <div className="flex justify-end gap-4 mt-6">
          <Button variant="outline" onClick={() => setShowAvailabilityModal(false)}>
            Close
          </Button>
        </div>
      </Modal>
    </div>
  );
}

