/**
 * Product Prices List Page
 * View and manage product prices
 */

'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { pricingAPI } from '@/lib/api/pricing';
import { productsAPI } from '@/lib/api/products';
import { Button, Card, CardHeader, CardTitle, CardContent, Table, TableHeader, TableBody, TableRow, TableHead, TableCell, Badge, LoadingSpinner, Select } from '@/components/ui';
import { formatCurrency } from '@/lib/utils/format';
import { Plus, DollarSign, Edit, Trash2 } from 'lucide-react';

export default function ProductPricesPage() {
  const router = useRouter();
  const [page, setPage] = useState(1);
  const [limit] = useState(20);
  const [priceListFilter, setPriceListFilter] = useState('');
  const [productFilter, setProductFilter] = useState('');
  const [activeFilter, setActiveFilter] = useState('true');

  // Fetch price lists for filter
  const { data: priceListsData } = useQuery({
    queryKey: ['price-lists', 'all'],
    queryFn: async () => {
      const response = await pricingAPI.listPriceLists({ limit: 100 });
      return response?.data || response;
    },
  });

  // Fetch products for filter
  const { data: productsData } = useQuery({
    queryKey: ['products', 'all'],
    queryFn: async () => {
      const response = await productsAPI.list({ limit: 100 });
      return response?.data || response;
    },
  });

  // Fetch product prices
  const { data, isLoading, error } = useQuery({
    queryKey: ['product-prices', page, limit, priceListFilter, productFilter, activeFilter],
    queryFn: async () => {
      const params = {
        page,
        limit,
        ...(priceListFilter && { price_list_id: priceListFilter }),
        ...(productFilter && { product_id: productFilter }),
        ...(activeFilter !== '' && { active: activeFilter }),
      };
      const response = await pricingAPI.listProductPrices(params);
      return response?.data || response;
    },
  });

  const priceLists = priceListsData?.priceLists || priceListsData?.price_lists || [];
  const products = productsData?.products || [];
  const productPrices = data?.productPrices || data?.product_prices || [];
  const pagination = data?.pagination || {};

  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">Product Prices</h1>
          <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
            Manage product pricing across price lists
          </p>
        </div>
        <Button
          onClick={() => router.push('/pricing/prices/new')}
          variant="primary"
          className="flex items-center gap-2"
        >
          <Plus className="w-5 h-5" />
          New Price
        </Button>
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="pt-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Price List
              </label>
              <Select
                value={priceListFilter}
                onChange={(e) => {
                  setPriceListFilter(e.target.value);
                  setPage(1);
                }}
              >
                <option value="">All Price Lists</option>
                {priceLists.map((pl) => (
                  <option key={pl.id} value={pl.id}>
                    {pl.name}
                  </option>
                ))}
              </Select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Product
              </label>
              <Select
                value={productFilter}
                onChange={(e) => {
                  setProductFilter(e.target.value);
                  setPage(1);
                }}
              >
                <option value="">All Products</option>
                {products.map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.name}
                  </option>
                ))}
              </Select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Status
              </label>
              <Select
                value={activeFilter}
                onChange={(e) => {
                  setActiveFilter(e.target.value);
                  setPage(1);
                }}
              >
                <option value="true">Active</option>
                <option value="false">Inactive</option>
                <option value="">All</option>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Product Prices Table */}
      <Card>
        <CardHeader>
          <CardTitle>Product Prices</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 product prices. Please try again.
            </div>
          ) : productPrices.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-gray-400">
              <DollarSign className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>No product prices found</p>
              <Button
                variant="primary"
                className="mt-4"
                onClick={() => router.push('/pricing/prices/new')}
              >
                Create Your First Price
              </Button>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Product</TableHead>
                    <TableHead>Price List</TableHead>
                    <TableHead align="right">Price</TableHead>
                    <TableHead>Quantity Range</TableHead>
                    <TableHead>Effective Dates</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead align="right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {productPrices.map((price) => (
                    <TableRow key={price.id}>
                      <TableCell>
                        <div className="font-medium">
                          {price.product?.name || 'Unknown Product'}
                        </div>
                      </TableCell>
                      <TableCell>
                        <span className="text-sm">{price.priceList?.name || 'N/A'}</span>
                      </TableCell>
                      <TableCell align="right" className="font-medium">
                        {formatCurrency(price.price)}
                      </TableCell>
                      <TableCell>
                        {price.min_quantity || 1}
                        {price.max_quantity ? ` - ${price.max_quantity}` : '+'}
                      </TableCell>
                      <TableCell className="text-sm text-gray-600 dark:text-gray-400">
                        {new Date(price.effective_from).toLocaleDateString()}
                        {price.effective_to && ` - ${new Date(price.effective_to).toLocaleDateString()}`}
                      </TableCell>
                      <TableCell>
                        {price.active ? (
                          <Badge variant="success">Active</Badge>
                        ) : (
                          <Badge variant="default">Inactive</Badge>
                        )}
                      </TableCell>
                      <TableCell align="right">
                        <div className="flex gap-2 justify-end">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => router.push(`/pricing/prices/${price.id}`)}
                          >
                            View
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => router.push(`/pricing/prices/${price.id}/edit`)}
                          >
                            <Edit className="w-4 h-4" />
                          </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} prices
                  </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>
  );
}
