/**
 * RM Inventory Pieces Page
 * View dimension-based RM inventory pieces for a specific product
 */

'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useRouter, useParams } from 'next/navigation';
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, Select } from '@/components/ui';
import { formatNumber, formatDate } from '@/lib/utils/format';
import { ArrowLeft, Package, Filter } from 'lucide-react';

export default function RMPiecesPage() {
  const router = useRouter();
  const params = useParams();
  const productId = parseInt(params.productId);
  
  const [page, setPage] = useState(1);
  const [limit] = useState(50);
  const [statusFilter, setStatusFilter] = useState('');

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

  // Fetch inventory pieces
  const { data, isLoading, error } = useQuery({
    queryKey: ['rm-pieces', productId, page, limit, statusFilter],
    queryFn: async () => {
      const params = {
        page,
        limit,
        ...(statusFilter && { status: statusFilter }),
      };
      const response = await inventoryAPI.listRMPieces(productId, params);
      return response?.data || response;
    },
    enabled: !!productId,
  });

  const pieces = data?.pieces || [];
  const pagination = data?.pagination || {};
  const product = productData;

  const getStatusBadge = (status) => {
    const variants = {
      FULL: 'success',
      USABLE: 'info',
      WASTE: 'warning',
      SCRAP: 'error',
    };
    return <Badge variant={variants[status] || 'secondary'}>{status}</Badge>;
  };

  const calculateArea = (piece) => {
    if (piece.status === 'FULL') {
      return piece.length * piece.width;
    } else if (piece.status === 'USABLE' && piece.usable_length && piece.usable_width) {
      return piece.usable_length * piece.usable_width;
    }
    return 0;
  };

  return (
    <div className="p-6 space-y-6 bg-gray-50 dark:bg-gray-950">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button
          variant="outline"
          size="sm"
          onClick={() => router.back()}
        >
          <ArrowLeft className="w-4 h-4 mr-2" />
          Back
        </Button>
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
            {product?.name || 'RM Inventory Pieces'}
          </h1>
          <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
            {product?.sku && `SKU: ${product.sku}`}
            {product?.unit_of_measure && ` • Unit: ${product.unit_of_measure}`}
          </p>
        </div>
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex gap-4 items-end">
            <div className="flex-1">
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Filter by Status
              </label>
              <Select
                value={statusFilter}
                onChange={(e) => {
                  setStatusFilter(e.target.value);
                  setPage(1);
                }}
              >
                <option value="">All Statuses</option>
                <option value="FULL">FULL</option>
                <option value="USABLE">USABLE</option>
                <option value="WASTE">WASTE</option>
                <option value="SCRAP">SCRAP</option>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Pieces Table */}
      <Card>
        <CardHeader>
          <CardTitle>Inventory Pieces</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading || productLoading ? (
            <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 pieces. Please try again.
            </div>
          ) : pieces.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 pieces found</p>
              {statusFilter && (
                <p className="text-sm mt-2">Try removing the status filter</p>
              )}
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Piece ID</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Dimensions</TableHead>
                    <TableHead>Usable Dimensions</TableHead>
                    <TableHead align="right">Area</TableHead>
                    <TableHead>GRN</TableHead>
                    <TableHead>Created At</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {pieces.map((piece) => {
                    const area = calculateArea(piece);
                    return (
                      <TableRow key={piece.id}>
                        <TableCell className="font-mono text-sm">
                          #{piece.id}
                        </TableCell>
                        <TableCell>
                          {getStatusBadge(piece.status)}
                        </TableCell>
                        <TableCell>
                          <div className="font-medium">
                            {formatNumber(piece.length, 3)} × {formatNumber(piece.width, 3)} {piece.unit || 'm'}
                          </div>
                          <div className="text-xs text-gray-500 dark:text-gray-400">
                            Base area: {formatNumber(piece.length * piece.width, 2)} {piece.unit || 'm'}²
                          </div>
                        </TableCell>
                        <TableCell>
                          {piece.status === 'FULL' ? (
                            <span className="text-gray-400">Full piece</span>
                          ) : piece.usable_length && piece.usable_width ? (
                            <div>
                              <div className="font-medium">
                                {formatNumber(piece.usable_length, 3)} × {formatNumber(piece.usable_width, 3)} {piece.unit || 'm'}
                              </div>
                              <div className="text-xs text-gray-500 dark:text-gray-400">
                                Usable area: {formatNumber(area, 2)} {piece.unit || 'm'}²
                              </div>
                            </div>
                          ) : (
                            <span className="text-gray-400">N/A</span>
                          )}
                        </TableCell>
                        <TableCell align="right">
                          <span className="font-medium">
                            {formatNumber(area, 2)} {piece.unit || 'm'}²
                          </span>
                        </TableCell>
                        <TableCell>
                          {piece.grnItem ? (
                            <div>
                              <div className="text-sm font-medium">
                                GRN #{piece.grnItem.grn_id}
                              </div>
                              {piece.grnItem.supplier_batch && (
                                <div className="text-xs text-gray-500 dark:text-gray-400">
                                  Batch: {piece.grnItem.supplier_batch}
                                </div>
                              )}
                            </div>
                          ) : (
                            <span className="text-gray-400">N/A</span>
                          )}
                        </TableCell>
                        <TableCell>
                          {formatDate(piece.created_at)}
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>

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