/**
 * Price List Detail Page
 * View price list details and manage product prices
 */

'use client';

import { useParams, useRouter } from 'next/navigation';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { pricingAPI } from '@/lib/api/pricing';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  Badge,
  LoadingPage,
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHead,
  TableCell,
  Modal,
} from '@/components/ui';
import { formatCurrency, formatDateTime, formatDate } from '@/lib/utils/format';
import { ArrowLeft, Edit, Trash2, Plus } from 'lucide-react';
import { useState } from 'react';
import toast from 'react-hot-toast';

export default function PriceListDetailPage() {
  const router = useRouter();
  const params = useParams();
  const priceListId = parseInt(params.id);
  const queryClient = useQueryClient();
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [pricesPage, setPricesPage] = useState(1);
  const [limit] = useState(20);

  // Fetch price list details
  const { data: priceList, isLoading, error } = useQuery({
    queryKey: ['price-list', priceListId],
    queryFn: async () => {
      if (isNaN(priceListId)) {
        throw new Error('Invalid price list ID');
      }
      const response = await pricingAPI.getPriceList(priceListId);
      return response?.data?.priceList || response?.data || response;
    },
    enabled: !isNaN(priceListId),
  });

  // Fetch product prices for this price list
  const { data: pricesData, isLoading: isLoadingPrices } = useQuery({
    queryKey: ['product-prices', priceListId, pricesPage, limit],
    queryFn: async () => {
      const response = await pricingAPI.listProductPrices({
        price_list_id: priceListId,
        page: pricesPage,
        limit,
      });
      return response?.data || response;
    },
    enabled: !isNaN(priceListId),
  });

  // Handle different response structures: data.prices, data.productPrices, or direct prices array
  const productPrices = pricesData?.prices || pricesData?.productPrices || pricesData?.product_prices || [];
  const pricesPagination = pricesData?.pagination || {};

  const deletePriceListMutation = useMutation({
    mutationFn: async () => {
      return await pricingAPI.deletePriceList(priceListId);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['price-lists']);
      toast.success('Price list deleted successfully!');
      router.push('/pricing');
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to delete price list';
      toast.error(message);
      setShowDeleteModal(false);
    },
  });

  const handleDelete = () => {
    deletePriceListMutation.mutate();
  };

  if (isLoading) {
    return <LoadingPage message="Loading price list details..." />;
  }

  if (error) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-red-600">
        <p>Error: {error.message}</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  if (!priceList) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-gray-600">
        <p>Price list not found.</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6 max-w-6xl">
      <div className="flex justify-between items-center mb-6">
        <Button variant="ghost" onClick={() => router.back()} className="flex items-center">
          <ArrowLeft className="w-4 h-4 mr-2" /> Back to Pricing
        </Button>
        <div className="flex gap-2">
          <Button
            variant="outline"
            onClick={() => router.push(`/pricing/price-lists/${priceListId}/edit`)}
            className="flex items-center gap-2"
          >
            <Edit className="w-4 h-4" />
            Edit
          </Button>
          <Button
            variant="primary"
            onClick={() => router.push(`/pricing/price-lists/${priceListId}/prices/new`)}
            className="flex items-center gap-2"
          >
            <Plus className="w-4 h-4" />
            Add Product Price
          </Button>
          <Button
            variant="outline"
            onClick={() => setShowDeleteModal(true)}
            className="flex items-center gap-2 text-red-600 hover:text-red-700"
          >
            <Trash2 className="w-4 h-4" />
            Delete
          </Button>
        </div>
      </div>

      {/* Price List Information */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>Price List Details</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">Basic Information</h3>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Name</p>
                  <p className="font-medium">{priceList.name}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Code</p>
                  <p className="font-mono font-medium">{priceList.code}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Type</p>
                  <Badge variant="info">{priceList.price_list_type}</Badge>
                </div>
                {priceList.description && (
                  <div>
                    <p className="text-sm text-gray-600 dark:text-gray-400">Description</p>
                    <p className="font-medium">{priceList.description}</p>
                  </div>
                )}
              </div>
            </div>

            <div>
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">Status & Settings</h3>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Currency</p>
                  <p className="font-medium">{priceList.currency || 'KES'}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Status</p>
                  <Badge variant={priceList.active ? 'success' : 'danger'}>
                    {priceList.active ? 'Active' : 'Inactive'}
                  </Badge>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Default</p>
                  {priceList.is_default ? (
                    <Badge variant="primary">Default Price List</Badge>
                  ) : (
                    <span className="text-gray-400">No</span>
                  )}
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Created</p>
                  <p className="font-medium">
                    {priceList.created_at ? formatDateTime(priceList.created_at) : '—'}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Product Prices */}
      <Card>
        <CardHeader>
          <CardTitle>Product Prices</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoadingPrices ? (
            <div className="flex justify-center py-12">
              <LoadingPage message="Loading product prices..." />
            </div>
          ) : productPrices.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-gray-400">
              <p>No product prices found</p>
              <Button
                variant="primary"
                className="mt-4"
                onClick={() => router.push(`/pricing/price-lists/${priceListId}/prices/new`)}
              >
                Add First Product Price
              </Button>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Product</TableHead>
                    <TableHead>Variant</TableHead>
                    <TableHead align="right">Price</TableHead>
                    <TableHead align="right">Min Qty</TableHead>
                    <TableHead align="right">Max Qty</TableHead>
                    <TableHead>Effective From</TableHead>
                    <TableHead>Effective To</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 || `Product #${price.product_id}`}
                        </div>
                        {price.product?.sku && (
                          <div className="text-xs text-gray-500 font-mono">{price.product.sku}</div>
                        )}
                      </TableCell>
                      <TableCell>
                        {price.variant ? (
                          <div>
                            <Badge variant="info">Variant</Badge>
                            <div className="text-xs text-gray-500 mt-1">{price.variant.name}</div>
                          </div>
                        ) : (
                          <span className="text-gray-400">Standard</span>
                        )}
                      </TableCell>
                      <TableCell align="right">
                        <span className="font-medium text-lg">
                          {formatCurrency(price.price, priceList.currency || 'KES')}
                        </span>
                      </TableCell>
                      <TableCell align="right">
                        {price.min_quantity || '1'}
                      </TableCell>
                      <TableCell align="right">
                        {price.max_quantity || '∞'}
                      </TableCell>
                      <TableCell>
                        {price.effective_from ? formatDate(price.effective_from) : '—'}
                      </TableCell>
                      <TableCell>
                        {price.effective_to ? formatDate(price.effective_to) : 'Ongoing'}
                      </TableCell>
                      <TableCell>
                        <Badge variant={price.active ? 'success' : 'danger'}>
                          {price.active ? 'Active' : 'Inactive'}
                        </Badge>
                      </TableCell>
                      <TableCell align="right">
                        <div className="flex justify-end gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => router.push(`/pricing/prices/${price.id}/edit`)}
                          >
                            Edit
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => router.push(`/pricing/prices/${price.id}`)}
                          >
                            View
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>

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

      {/* Delete Modal */}
      <Modal
        isOpen={showDeleteModal}
        onClose={() => setShowDeleteModal(false)}
        title="Delete Price List"
      >
        <div className="space-y-4">
          <p className="text-gray-700 dark:text-gray-300">
            Are you sure you want to delete the price list <strong>{priceList.name}</strong>?
          </p>
          <p className="text-sm text-gray-500">
            This action cannot be undone. If this price list has product prices or is assigned to customers, the deletion will fail.
          </p>
          <div className="flex justify-end gap-4 pt-4 border-t">
            <Button
              variant="outline"
              onClick={() => setShowDeleteModal(false)}
              disabled={deletePriceListMutation.isLoading}
            >
              Cancel
            </Button>
            <Button
              variant="danger"
              onClick={handleDelete}
              disabled={deletePriceListMutation.isLoading}
              loading={deletePriceListMutation.isLoading}
            >
              Delete
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}

