/**
 * Inventory List Page
 * View and manage inventory - Split by product type (RM/FG) with UID tracking
 */

'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { inventoryAPI } from '@/lib/api/inventory';
import { Button, Card, CardHeader, CardTitle, CardContent, Table, TableHeader, TableBody, TableRow, TableHead, TableCell, Badge, LoadingSpinner } from '@/components/ui';
import { formatNumber } from '@/lib/utils/format';
import { Warehouse, AlertTriangle, Package, Box } from 'lucide-react';

export default function InventoryPage() {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState('finished-goods'); // 'raw-materials' or 'finished-goods'
  const [page, setPage] = useState(1);
  const [limit] = useState(50);
  const [lowStockFilter, setLowStockFilter] = useState('');
  const [outOfStockFilter, setOutOfStockFilter] = useState('');

  // Fetch inventory filtered by product type
  const { data, isLoading, error } = useQuery({
    queryKey: ['inventory', activeTab, page, limit, lowStockFilter, outOfStockFilter],
    queryFn: async () => {
      const params = {
        page,
        limit,
        product_type: activeTab === 'raw-materials' ? 'RM' : 'FG', // Filter by product type
        ...(lowStockFilter === 'true' && { low_stock: 'true' }),
        ...(outOfStockFilter === 'true' && { out_of_stock: 'true' }),
      };
      const response = await inventoryAPI.list(params);
      return response.data || response;
    },
  });

  const inventoryItems = data?.inventories || data?.inventory || [];
  const pagination = data?.pagination || {};

  const getStockStatus = (item) => {
    if (item.quantity <= 0) {
      return { label: 'Out of Stock', variant: 'danger' };
    }
    if (item.reorder_level && item.quantity <= item.reorder_level) {
      return { label: 'Low Stock', variant: 'warning' };
    }
    return { label: 'In Stock', variant: 'success' };
  };

  return (
    <div className="p-6 space-y-6 bg-gray-50 dark:bg-gray-950">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Inventory Management</h1>
          <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
            Manage inventory levels for Raw Materials and Finished Goods
          </p>
        </div>
        <Button
          variant="outline"
          onClick={() => router.push('/inventory/reconciliation')}
        >
          <AlertTriangle className="w-4 h-4 mr-2" />
          Reconciliation
        </Button>
      </div>

      {/* Product Type Tabs */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex gap-2 border-b border-gray-200 dark:border-gray-700">
            <button
              onClick={() => {
                setActiveTab('finished-goods');
                setPage(1);
              }}
              className={`flex items-center gap-2 px-4 py-2 font-medium transition-colors border-b-2 ${
                activeTab === 'finished-goods'
                  ? 'border-blue-600 text-blue-600 dark:text-blue-400 dark:border-blue-400'
                  : 'border-transparent text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-200'
              }`}
            >
              <Package className="w-4 h-4" />
              Finished Goods (FG)
            </button>
            <button
              onClick={() => {
                setActiveTab('raw-materials');
                setPage(1);
              }}
              className={`flex items-center gap-2 px-4 py-2 font-medium transition-colors border-b-2 ${
                activeTab === 'raw-materials'
                  ? 'border-blue-600 text-blue-600 dark:text-blue-400 dark:border-blue-400'
                  : 'border-transparent text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-200'
              }`}
            >
              <Box className="w-4 h-4" />
              Raw Materials (RM)
            </button>
          </div>
        </CardContent>
      </Card>

      {/* Filters */}
      <Card>
        <CardContent className="pt-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Stock Status
              </label>
              <select
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                value={lowStockFilter}
                onChange={(e) => {
                  setLowStockFilter(e.target.value);
                  setOutOfStockFilter(''); // Clear other filter
                  setPage(1);
                }}
              >
                <option value="">All Items</option>
                <option value="true">Low Stock</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Availability
              </label>
              <select
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                value={outOfStockFilter}
                onChange={(e) => {
                  setOutOfStockFilter(e.target.value);
                  setLowStockFilter(''); // Clear other filter
                  setPage(1);
                }}
              >
                <option value="">All Items</option>
                <option value="true">Out of Stock</option>
              </select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Inventory Table */}
      <Card>
        <CardHeader>
          <CardTitle>
            {activeTab === 'finished-goods' ? 'Finished Goods Inventory' : 'Raw Materials Inventory'}
          </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. Please try again.
            </div>
          ) : inventoryItems.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-gray-400">
              <Warehouse className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>No inventory items found</p>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Product</TableHead>
                    <TableHead>Variant</TableHead>
                    <TableHead align="right">Quantity</TableHead>
                    <TableHead>UID Tracking</TableHead>
                    <TableHead align="right">Reorder Level</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead align="right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {inventoryItems.map((item) => {
                    const stockStatus = getStockStatus(item);
                    const tracksUID = item.product?.track_inventory;
                    // Use product_id as key since dimension-based items have null id
                    const rowKey = item.id !== null ? item.id : `dim-${item.product_id}`;
                    return (
                      <TableRow key={rowKey}>
                        <TableCell>
                          <div>
                            <div className="font-medium">
                              {item.product?.name || 'Unknown Product'}
                            </div>
                            {item.product?.sku && (
                              <div className="text-xs text-gray-500 dark:text-gray-400 font-mono">
                                SKU: {item.product.sku}
                              </div>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          {item.variant ? (
                            <div>
                              <Badge variant="info">Variant</Badge>
                              {item.variant.attributes && (
                                <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                  {Object.entries(item.variant.attributes)
                                    .map(([key, value]) => `${key}: ${value}`)
                                    .join(', ')}
                                </div>
                              )}
                            </div>
                          ) : (
                            <span className="text-gray-400 dark:text-gray-500">Standard</span>
                          )}
                        </TableCell>
                        <TableCell align="right">
                          {item._isDimensionBased ? (
                            <div className="text-right">
                              <div className="font-medium text-lg">{formatNumber(item.quantity, 0)} pieces</div>
                              <div className="text-xs text-gray-500 dark:text-gray-400">
                                {formatNumber(item._totalArea || 0, 2)} {item._unit || 'm'}²
                              </div>
                            </div>
                          ) : (
                            <span className="font-medium text-lg">{formatNumber(item.quantity, 0)}</span>
                          )}
                        </TableCell>
                        <TableCell>
                          {item._isDimensionBased ? (
                            <div className="flex flex-col gap-1">
                              <Badge variant="info" className="w-fit">
                                Dimension-Based
                              </Badge>
                              <span className="text-xs text-gray-500 dark:text-gray-400">
                                {item.quantity || 0} pieces
                              </span>
                            </div>
                          ) : tracksUID ? (
                            <div className="flex flex-col gap-1">
                              <Badge variant="success" className="w-fit">
                                UID Tracked
                              </Badge>
                              <span className="text-xs text-gray-500 dark:text-gray-400">
                                {item.quantity || 0} unique items
                              </span>
                            </div>
                          ) : (
                            <Badge variant="secondary" className="w-fit">
                              Quantity Only
                            </Badge>
                          )}
                        </TableCell>
                        <TableCell align="right">
                          <span className="text-gray-600 dark:text-gray-400">
                            {item.reorder_level ? formatNumber(item.reorder_level, 0) : 'N/A'}
                          </span>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <Badge variant={stockStatus.variant}>
                              {stockStatus.label}
                            </Badge>
                            {stockStatus.variant === 'warning' && (
                              <AlertTriangle className="w-4 h-4 text-yellow-500" />
                            )}
                          </div>
                        </TableCell>
                        <TableCell align="right">
                          <div className="flex gap-2 justify-end">
                            {item._isDimensionBased ? (
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => router.push(`/inventory/rm/${item.product_id}/pieces`)}
                                title="View dimension-based inventory pieces"
                              >
                                View Pieces
                              </Button>
                            ) : tracksUID ? (
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => router.push(`/inventory/items?product_id=${item.product_id}${item.variant_id ? `&variant_id=${item.variant_id}` : ''}`)}
                                title="View UID items"
                              >
                                View UIDs
                              </Button>
                            ) : null}
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => router.push(`/products/${item.product_id}${item.variant_id ? `?variant=${item.variant_id}` : ''}`)}
                            >
                              View Product
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>

              {/* 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>
    </div>
  );
}

