/**
 * Inventory Items (UID) Page
 * View and manage individual inventory items with unique identifiers
 */

'use client';

import { useState } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { inventoryAPI } from '@/lib/api/inventory';
import { productsAPI } from '@/lib/api/products';
import { Button, Card, CardHeader, CardTitle, CardContent, Table, TableHeader, TableBody, TableRow, TableHead, TableCell, Badge, LoadingSpinner, Input, Modal } from '@/components/ui';
import { ArrowLeft, Package, Barcode, QrCode, Search, Filter, Printer } from 'lucide-react';
import toast from 'react-hot-toast';
import { usePrintLabel } from '@/hooks/usePrintLabel';
import PrinterSelect from '@/components/features/label-printing/PrinterSelect';

const STATUS_COLORS = {
  IN_STOCK: 'success',
  RESERVED: 'warning',
  SOLD: 'secondary',
  RETURNED: 'info',
  DAMAGED: 'danger',
  SCRAPPED: 'secondary',
};

const STATUS_LABELS = {
  IN_STOCK: 'In Stock',
  RESERVED: 'Reserved',
  SOLD: 'Sold',
  RETURNED: 'Returned',
  DAMAGED: 'Damaged',
  SCRAPPED: 'Scrapped',
};

export default function InventoryItemsPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const productId = searchParams.get('product_id') ? parseInt(searchParams.get('product_id')) : null;
  const variantId = searchParams.get('variant_id') ? parseInt(searchParams.get('variant_id')) : null;

  const [page, setPage] = useState(1);
  const [limit] = useState(50);
  const [statusFilter, setStatusFilter] = useState('');
  const [uidSearch, setUidSearch] = useState('');
  const [barcodeSearch, setBarcodeSearch] = useState('');
  const [showPrintModal, setShowPrintModal] = useState(false);
  const [selectedItemForPrint, setSelectedItemForPrint] = useState(null);
  const { printLabel, isPrinting, selectedPrinterName, setSelectedPrinterName } = usePrintLabel();

  // Fetch product details
  const { data: productData, isLoading: productLoading } = useQuery({
    queryKey: ['product', productId],
    queryFn: async () => {
      if (!productId) return null;
      const response = await productsAPI.getById(productId);
      return response?.data?.product || response?.data || response;
    },
    enabled: !!productId,
  });

  // Fetch inventory items
  const { data, isLoading, error } = useQuery({
    queryKey: ['inventory-items', productId, variantId, page, limit, statusFilter, uidSearch, barcodeSearch],
    queryFn: async () => {
      const params = {
        page,
        limit,
        ...(productId && { product_id: productId }),
        ...(variantId !== null && { variant_id: variantId }),
        ...(statusFilter && { status: statusFilter }),
        ...(uidSearch && { uid: uidSearch }),
        ...(barcodeSearch && { barcode: barcodeSearch }),
      };
      const response = await inventoryAPI.listItems(params);
      return response?.data || response;
    },
    enabled: !!productId,
  });

  const inventoryItems = data?.items || data?.inventoryItems || [];
  const pagination = data?.pagination || {};
  const statusCounts = data?.statusCounts || null; // Status counts from API (for all items, not just current page)

  const handleUIDSearch = (e) => {
    e.preventDefault();
    if (uidSearch.trim()) {
      setUidSearch(uidSearch.trim());
      setPage(1);
    }
  };

  const handleBarcodeSearch = (e) => {
    e.preventDefault();
    if (barcodeSearch.trim()) {
      setBarcodeSearch(barcodeSearch.trim());
      setPage(1);
    }
  };

  const handlePrintLabel = (inventoryItem) => {
    // Only allow printing for FG products
    if (productData?.product_type !== 'FG') {
      toast.error('Labels can only be printed for Finished Goods (FG) products');
      return;
    }
    
    setSelectedItemForPrint(inventoryItem);
    setShowPrintModal(true);
  };

  const handleConfirmPrint = () => {
    if (!selectedPrinterName) {
      toast.error('Please select a printer');
      return;
    }
    
    if (!selectedItemForPrint) {
      toast.error('No item selected for printing');
      return;
    }
    
    printLabel(
      { 
        inventoryItemId: selectedItemForPrint.id,
        printerName: selectedPrinterName 
      },
      {
        onSuccess: () => {
          setShowPrintModal(false);
          setSelectedItemForPrint(null);
        },
      }
    );
  };

  const clearFilters = () => {
    setStatusFilter('');
    setUidSearch('');
    setBarcodeSearch('');
    setPage(1);
  };

  const copyToClipboard = (text) => {
    navigator.clipboard.writeText(text);
    toast.success('Copied to clipboard');
  };

  if (!productId) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950">
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-12">
              <p className="text-red-600 dark:text-red-400 mb-4">Product ID is required</p>
              <Button onClick={() => router.push('/inventory')} variant="outline">
                Back to Inventory
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (productLoading) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950">
        <div className="flex justify-center py-12">
          <LoadingSpinner size="lg" />
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6 bg-gray-50 dark:bg-gray-950">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button
            variant="outline"
            onClick={() => router.push('/inventory')}
            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">Inventory Items (UIDs)</h1>
            <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
              {productData?.name || 'Product'} {variantId && '(Variant)'}
            </p>
            {productData?.sku && (
              <p className="text-xs text-gray-500 dark:text-gray-400 font-mono mt-1">
                SKU: {productData.sku}
              </p>
            )}
          </div>
        </div>
      </div>

      {/* Filters */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Filter className="w-5 h-5" />
            Filters & Search
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            {/* Status Filter */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Status
              </label>
              <select
                className="w-full px-4 py-2 border border-gray-300 dark:border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:text-white"
                value={statusFilter}
                onChange={(e) => {
                  setStatusFilter(e.target.value);
                  setPage(1);
                }}
              >
                <option value="">All Statuses</option>
                <option value="IN_STOCK">In Stock</option>
                <option value="RESERVED">Reserved</option>
                <option value="SOLD">Sold</option>
                <option value="RETURNED">Returned</option>
                <option value="DAMAGED">Damaged</option>
                <option value="SCRAPPED">Scrapped</option>
              </select>
            </div>

            {/* UID Search */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Search by UID
              </label>
              <form onSubmit={handleUIDSearch} className="flex gap-2">
                <Input
                  type="text"
                  placeholder="Enter UID..."
                  value={uidSearch}
                  onChange={(e) => setUidSearch(e.target.value)}
                  leftIcon={<QrCode className="w-4 h-4" />}
                  className="flex-1"
                />
                <Button type="submit" variant="outline" size="sm">
                  <Search className="w-4 h-4" />
                </Button>
              </form>
            </div>

            {/* Barcode Search */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Search by Barcode
              </label>
              <form onSubmit={handleBarcodeSearch} className="flex gap-2">
                <Input
                  type="text"
                  placeholder="Enter barcode..."
                  value={barcodeSearch}
                  onChange={(e) => setBarcodeSearch(e.target.value)}
                  leftIcon={<Barcode className="w-4 h-4" />}
                  className="flex-1"
                />
                <Button type="submit" variant="outline" size="sm">
                  <Search className="w-4 h-4" />
                </Button>
              </form>
            </div>

            {/* Clear Filters */}
            <div className="flex items-end">
              <Button
                variant="outline"
                onClick={clearFilters}
                className="w-full"
                disabled={!statusFilter && !uidSearch && !barcodeSearch}
              >
                Clear Filters
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Stats */}
      {!isLoading && !error && (
        <div className="grid grid-cols-1 md:grid-cols-6 gap-4">
          <Card>
            <CardContent className="pt-6">
              <div className="text-center">
                <p className="text-2xl font-bold text-gray-900 dark:text-white">{pagination.total || 0}</p>
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">Total Items</p>
              </div>
            </CardContent>
          </Card>
          {Object.keys(STATUS_LABELS).map((status) => {
            // Use statusCounts from API if available (accurate), otherwise count from current page (approximate)
            const count = statusCounts ? (statusCounts[status] || 0) : inventoryItems.filter((item) => item.status === status).length;
            return (
              <Card key={status}>
                <CardContent className="pt-6">
                  <div className="text-center">
                    <p className="text-2xl font-bold text-gray-900 dark:text-white">{count}</p>
                    <Badge variant={STATUS_COLORS[status]} className="mt-1 text-xs">
                      {STATUS_LABELS[status]}
                    </Badge>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      {/* Inventory Items Table */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Package className="w-5 h-5" />
            Inventory Items
          </CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex justify-center py-12">
              <LoadingSpinner size="lg" />
            </div>
          ) : error ? (
            <div className="text-center py-12 text-red-600 dark:text-red-400">
              Error loading inventory items. Please try again.
            </div>
          ) : inventoryItems.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-gray-400">
              <Package className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>No inventory items found</p>
              {productId && (
                <p className="text-sm mt-2">
                  This product may not have UID tracking enabled, or no items have been added yet.
                </p>
              )}
            </div>
          ) : (
            <>
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>UID</TableHead>
                      <TableHead>Barcode</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead>Source</TableHead>
                      <TableHead>Created</TableHead>
                      <TableHead>Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {inventoryItems.map((item) => (
                      <TableRow key={item.id}>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <code className="text-sm font-mono bg-gray-100 dark:bg-gray-800 px-2 py-1 rounded">
                              {item.uid}
                            </code>
                            <button
                              onClick={() => copyToClipboard(item.uid)}
                              className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                              title="Copy UID"
                            >
                              <QrCode className="w-4 h-4" />
                            </button>
                          </div>
                        </TableCell>
                        <TableCell>
                          {item.barcode ? (
                            <div className="flex items-center gap-2">
                              <code className="text-sm font-mono bg-gray-100 dark:bg-gray-800 px-2 py-1 rounded">
                                {item.barcode}
                              </code>
                              <button
                                onClick={() => copyToClipboard(item.barcode)}
                                className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                                title="Copy Barcode"
                              >
                                <Barcode className="w-4 h-4" />
                              </button>
                            </div>
                          ) : (
                            <span className="text-gray-400 dark:text-gray-500">-</span>
                          )}
                        </TableCell>
                        <TableCell>
                          <Badge variant={STATUS_COLORS[item.status] || 'secondary'}>
                            {STATUS_LABELS[item.status] || item.status}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge variant="info">{item.source || '-'}</Badge>
                        </TableCell>
                        <TableCell>
                          <span className="text-sm text-gray-600 dark:text-gray-400">
                            {item.created_at
                              ? new Date(item.created_at).toLocaleDateString('en-US', {
                                  year: 'numeric',
                                  month: 'short',
                                  day: 'numeric',
                                })
                              : '-'}
                          </span>
                        </TableCell>
                        <TableCell>
                          <div className="flex gap-2">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => {
                                router.push(`/inventory/items/${item.uid}`);
                              }}
                            >
                              View Details
                            </Button>
                            {productData?.product_type === 'FG' && (
                              <Button
                                variant="primary"
                                size="sm"
                                onClick={() => handlePrintLabel(item)}
                                disabled={isPrinting}
                                loading={isPrinting}
                                title="Print label for this inventory item"
                              >
                                <Printer className="w-4 h-4 mr-1" />
                                Print Label
                              </Button>
                            )}
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {/* Pagination */}
              {pagination.totalPages > 1 && (
                <div className="mt-4 flex items-center justify-between">
                  <div className="text-sm text-gray-700 dark:text-gray-300">
                    Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, pagination.total)} of {pagination.total} items
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setPage(p => Math.max(1, p - 1))}
                      disabled={page === 1}
                    >
                      Previous
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setPage(p => Math.min(pagination.totalPages, p + 1))}
                      disabled={page === pagination.totalPages}
                    >
                      Next
                    </Button>
                  </div>
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>

      {/* Print Label Modal */}
      <Modal
        isOpen={showPrintModal}
        onClose={() => {
          setShowPrintModal(false);
          setSelectedItemForPrint(null);
        }}
        title="Print Label"
        description={`Print label for ${selectedItemForPrint?.uid || 'inventory item'}`}
      >
        <div className="space-y-4 mt-4">
          {selectedItemForPrint && (
            <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 text-blue-900 dark:text-blue-100">
                <strong>Product:</strong> {productData?.name || 'Unknown'}<br />
                <strong>UID:</strong> {selectedItemForPrint.uid}
              </p>
            </div>
          )}

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Select Printer
            </label>
            <PrinterSelect
              value={selectedPrinterName}
              onChange={(printerName) => {
                setSelectedPrinterName(printerName);
                // Printer selection is handled internally by PrinterSelect component
                // No need to save to localStorage - always query service fresh
              }}
              label="Select Label Printer"
              autoSelect={true}
            />
          </div>
        </div>
        <div className="flex justify-end gap-4 mt-6">
          <Button 
            variant="outline" 
            onClick={() => {
              setShowPrintModal(false);
              setSelectedItemForPrint(null);
            }}
          >
            Cancel
          </Button>
          <Button
            variant="primary"
            onClick={handleConfirmPrint}
            disabled={!selectedPrinterName || isPrinting}
            loading={isPrinting}
            className="flex items-center gap-2"
          >
            <Printer className="w-4 h-4" />
            Print Label
          </Button>
        </div>
      </Modal>
    </div>
  );
}

