/**
 * Product Price Detail Page
 * View product price details
 */

'use client';

import { useParams, useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { pricingAPI } from '@/lib/api/pricing';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  Badge,
  LoadingPage,
} from '@/components/ui';
import { formatCurrency, formatDateTime, formatDate } from '@/lib/utils/format';
import { ArrowLeft, Edit } from 'lucide-react';

export default function ProductPriceDetailPage() {
  const router = useRouter();
  const params = useParams();
  const priceId = parseInt(params.id);

  // Fetch product price details
  const { data: priceData, isLoading, error } = useQuery({
    queryKey: ['product-price', priceId],
    queryFn: async () => {
      if (isNaN(priceId)) {
        throw new Error('Invalid product price ID');
      }
      const response = await pricingAPI.getProductPrice(priceId);
      // API returns: { success: true, data: productPrice, message: "..." }
      return response?.data || response;
    },
    enabled: !isNaN(priceId),
  });

  if (isLoading) {
    return <LoadingPage message="Loading product price 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 (!priceData) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-gray-600">
        <p>Product price not found.</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  const productPrice = priceData;
  const priceList = productPrice.priceList || productPrice.price_list;
  const product = productPrice.product;
  const variant = productPrice.variant;

  return (
    <div className="container mx-auto p-6 max-w-4xl">
      <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
        </Button>
        <Button
          variant="primary"
          onClick={() => router.push(`/pricing/prices/${priceId}/edit`)}
          className="flex items-center gap-2"
        >
          <Edit className="w-4 h-4" />
          Edit Price
        </Button>
      </div>

      {/* Product Price Information */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>Product Price 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">Product Information</h3>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Product</p>
                  <p className="font-medium">{product?.name || `Product #${productPrice.product_id}`}</p>
                  {product?.sku && (
                    <p className="text-xs text-gray-500 font-mono mt-1">SKU: {product.sku}</p>
                  )}
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Variant</p>
                  {variant ? (
                    <div>
                      <Badge variant="info">Variant</Badge>
                      <p className="font-medium mt-1">{variant.name}</p>
                      {variant.sku && (
                        <p className="text-xs text-gray-500 font-mono mt-1">SKU: {variant.sku}</p>
                      )}
                    </div>
                  ) : (
                    <span className="text-gray-400">Standard (No Variant)</span>
                  )}
                </div>
              </div>
            </div>

            <div>
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">Price Information</h3>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Price</p>
                  <p className="font-bold text-2xl">
                    {formatCurrency(productPrice.price, priceList?.currency || 'KES')}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Price List</p>
                  <p className="font-medium">{priceList?.name || 'N/A'}</p>
                  {priceList?.code && (
                    <p className="text-xs text-gray-500 font-mono mt-1">{priceList.code}</p>
                  )}
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Status</p>
                  <Badge variant={productPrice.active ? 'success' : 'danger'}>
                    {productPrice.active ? 'Active' : 'Inactive'}
                  </Badge>
                </div>
              </div>
            </div>

            <div>
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">Quantity Range</h3>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Minimum Quantity</p>
                  <p className="font-medium">{productPrice.min_quantity || 1}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Maximum Quantity</p>
                  <p className="font-medium">{productPrice.max_quantity || '∞ (No limit)'}</p>
                </div>
              </div>
            </div>

            <div>
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">Effective Dates</h3>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Effective From</p>
                  <p className="font-medium">
                    {productPrice.effective_from ? formatDate(productPrice.effective_from) : '—'}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Effective To</p>
                  <p className="font-medium">
                    {productPrice.effective_to ? formatDate(productPrice.effective_to) : 'Ongoing'}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Created</p>
                  <p className="font-medium">
                    {productPrice.created_at ? formatDateTime(productPrice.created_at) : '—'}
                  </p>
                </div>
                {productPrice.updated_at && (
                  <div>
                    <p className="text-sm text-gray-600 dark:text-gray-400">Last Updated</p>
                    <p className="font-medium">{formatDateTime(productPrice.updated_at)}</p>
                  </div>
                )}
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Navigation */}
      <div className="flex justify-between">
        <Button
          variant="outline"
          onClick={() => {
            if (priceList?.id) {
              router.push(`/pricing/price-lists/${priceList.id}`);
            } else {
              router.back();
            }
          }}
        >
          View Price List
        </Button>
        <Button
          variant="primary"
          onClick={() => router.push(`/pricing/prices/${priceId}/edit`)}
        >
          Edit Price
        </Button>
      </div>
    </div>
  );
}

