/**
 * Production Orders List Page
 * View and manage production orders
 */

'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { productionAPI } from '@/lib/api/production';
import { Button, Card, CardHeader, CardTitle, CardContent, Table, TableHeader, TableBody, TableRow, TableHead, TableCell, Badge, LoadingSpinner, Input } from '@/components/ui';
import { formatDate, formatDateTime } from '@/lib/utils/format';
import { Package, Plus, Search } from 'lucide-react';

export default function ProductionOrdersPage() {
  const router = useRouter();
  const [page, setPage] = useState(1);
  const [limit] = useState(20);
  const [statusFilter, setStatusFilter] = useState('');

  // Fetch production orders
  const { data, isLoading, error } = useQuery({
    queryKey: ['production-orders', page, limit, statusFilter],
    queryFn: async () => {
      const params = {
        page,
        limit,
        ...(statusFilter && { status: statusFilter }),
      };
      const response = await productionAPI.listProductionOrders(params);
      return response?.data || response;
    },
  });

  const productionOrders = data?.productionOrders || data?.production_orders || [];
  const pagination = data?.pagination || {};

  const getStatusVariant = (status) => {
    switch (status) {
      case 'CONFIRMED':
        return 'success';
      case 'PARTIALLY_CONFIRMED':
        return 'warning';
      case 'DRAFT':
        return 'default';
      default:
        return 'default';
    }
  };

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-950 space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Production Orders</h1>
          <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
            Create and manage production orders
          </p>
        </div>
        <Button
          onClick={() => router.push('/production/orders/new')}
          variant="primary"
          className="flex items-center gap-2"
        >
          <Plus className="w-5 h-5" />
          New Production Order
        </Button>
      </div>

      {/* 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">
                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={statusFilter}
                onChange={(e) => {
                  setStatusFilter(e.target.value);
                  setPage(1);
                }}
              >
                <option value="">All Statuses</option>
                <option value="DRAFT">Draft</option>
                <option value="PARTIALLY_CONFIRMED">Partially Confirmed</option>
                <option value="CONFIRMED">Confirmed</option>
              </select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Production Orders Table */}
      <Card>
        <CardHeader>
          <CardTitle>Production Orders</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 production orders. Please try again.
            </div>
          ) : productionOrders.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 production orders found</p>
              <Button
                variant="primary"
                className="mt-4"
                onClick={() => router.push('/production/orders/new')}
              >
                Create Your First Production Order
              </Button>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Order #</TableHead>
                    <TableHead>Finished Good</TableHead>
                    <TableHead align="right">Order Qty</TableHead>
                    <TableHead align="right">Confirmed</TableHead>
                    <TableHead align="right">Remaining</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Created</TableHead>
                    <TableHead>Confirmed</TableHead>
                    <TableHead align="right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {productionOrders.map((order) => (
                    <TableRow key={order.id}>
                      <TableCell>
                        <span className="font-mono font-medium">PO-{order.id}</span>
                      </TableCell>
                      <TableCell>
                        <div className="font-medium">
                          {order.finishedGoodProduct?.name || order.finishedGoodVariant?.product?.name || 'Unknown Product'}
                        </div>
                        {order.finishedGoodProduct?.sku && (
                          <div className="text-xs text-gray-500">
                            SKU: {order.finishedGoodProduct.sku}
                          </div>
                        )}
                        {order.finishedGoodVariant?.name && (
                          <div className="text-xs text-gray-500">
                            Variant: {order.finishedGoodVariant.name}
                          </div>
                        )}
                      </TableCell>
                      <TableCell align="right" className="font-medium">
                        {Math.floor(order.quantity || 0)}
                      </TableCell>
                      <TableCell align="right" className="font-medium text-green-600">
                        {order.confirmed_quantity !== undefined && order.confirmed_quantity !== null 
                          ? Math.floor(order.confirmed_quantity) 
                          : '—'}
                      </TableCell>
                      <TableCell align="right" className="font-medium text-orange-600">
                        {(order.remaining_quantity !== undefined && order.remaining_quantity !== null && order.remaining_quantity > 0)
                          ? Math.floor(order.remaining_quantity)
                          : order.status === 'CONFIRMED' ? '0' : '—'}
                      </TableCell>
                      <TableCell>
                        <Badge variant={getStatusVariant(order.status)}>
                          {order.status === 'PARTIALLY_CONFIRMED' ? 'PARTIAL' : order.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-sm text-gray-600 dark:text-gray-400">
                        {order.created_at ? formatDate(order.created_at) : '—'}
                      </TableCell>
                      <TableCell className="text-sm text-gray-600 dark:text-gray-400">
                        {order.confirmed_at ? formatDate(order.confirmed_at) : '—'}
                      </TableCell>
                      <TableCell align="right">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => router.push(`/production/orders/${order.id}`)}
                        >
                          View
                        </Button>
                      </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} orders
                  </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>
  );
}

