/**
 * Edit Product Price Page
 * Edit an existing product price
 */

'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { pricingAPI } from '@/lib/api/pricing';
import { productsAPI } from '@/lib/api/products';
import { Button, Card, CardHeader, CardTitle, CardContent, Input, LoadingPage } from '@/components/ui';
import { ArrowLeft } from 'lucide-react';
import toast from 'react-hot-toast';

const productPriceSchema = z.object({
  price: z.number().positive('Price must be greater than 0'),
  min_quantity: z.number().min(1, 'Minimum quantity must be at least 1').default(1),
  max_quantity: z.number().positive().nullable().optional(),
  effective_from: z.string().min(1, 'Effective from date is required'),
  effective_to: z.string().optional(),
  active: z.boolean().default(true),
}).refine((data) => {
  // If max_quantity is provided, it must be >= min_quantity
  if (data.max_quantity && data.max_quantity < data.min_quantity) {
    return false;
  }
  return true;
}, {
  message: 'Maximum quantity must be greater than or equal to minimum quantity',
  path: ['max_quantity'],
});

export default function EditProductPricePage() {
  const router = useRouter();
  const params = useParams();
  const priceId = parseInt(params.id);
  const queryClient = useQueryClient();
  const [isSubmitting, setIsSubmitting] = useState(false);

  // 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),
  });

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

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(productPriceSchema),
    defaultValues: {
      price: 0,
      min_quantity: 1,
      max_quantity: undefined,
      effective_from: new Date().toISOString().split('T')[0],
      effective_to: '',
      active: true,
    },
  });

  // Reset form when product price data loads
  useEffect(() => {
    if (productPrice) {
      reset({
        price: parseFloat(productPrice.price) || 0,
        min_quantity: parseInt(productPrice.min_quantity) || 1,
        max_quantity: productPrice.max_quantity ? parseInt(productPrice.max_quantity) : undefined,
        effective_from: productPrice.effective_from
          ? new Date(productPrice.effective_from).toISOString().split('T')[0]
          : new Date().toISOString().split('T')[0],
        effective_to: productPrice.effective_to
          ? new Date(productPrice.effective_to).toISOString().split('T')[0]
          : '',
        active: productPrice.active !== undefined ? productPrice.active : true,
      });
    }
  }, [productPrice, reset]);

  const updateProductPriceMutation = useMutation({
    mutationFn: async (data) => {
      const priceData = {
        price: parseFloat(data.price),
        min_quantity: parseFloat(data.min_quantity) || 1,
        max_quantity: data.max_quantity ? parseFloat(data.max_quantity) : null,
        effective_from: data.effective_from ? new Date(data.effective_from).toISOString() : undefined,
        effective_to: data.effective_to ? new Date(data.effective_to).toISOString() : null,
        active: data.active,
      };
      return await pricingAPI.updateProductPrice(priceId, priceData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['product-price', priceId]);
      if (priceList?.id) {
        queryClient.invalidateQueries(['product-prices', priceList.id]);
        queryClient.invalidateQueries(['price-list', priceList.id]);
      }
      toast.success('Product price updated successfully!');
      router.push(`/pricing/prices/${priceId}`);
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to update product price';
      toast.error(message);
    },
    onSettled: () => {
      setIsSubmitting(false);
    },
  });

  const onSubmit = async (data) => {
    setIsSubmitting(true);
    updateProductPriceMutation.mutate(data);
  };

  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 (!productPrice) {
    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>
    );
  }

  return (
    <div className="container mx-auto p-6 max-w-4xl">
      <div className="mb-6">
        <Button variant="ghost" onClick={() => router.back()} className="flex items-center">
          <ArrowLeft className="w-4 h-4 mr-2" /> Back
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Edit Product Price</CardTitle>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-2">
            {product?.name && (
              <>
                <strong>Product:</strong> {product.name}
                {product.sku && ` (${product.sku})`}
              </>
            )}
            {variant && (
              <>
                {' • '}
                <strong>Variant:</strong> {variant.name}
              </>
            )}
            {priceList?.name && (
              <>
                {' • '}
                <strong>Price List:</strong> {priceList.name}
              </>
            )}
          </p>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Price ({priceList?.currency || 'KES'}) *
                </label>
                <Input
                  type="number"
                  step="0.01"
                  min="0"
                  {...register('price', { valueAsNumber: true })}
                  placeholder="0.00"
                  error={errors.price?.message}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Minimum Quantity *
                </label>
                <Input
                  type="number"
                  step="1"
                  min="1"
                  {...register('min_quantity', { valueAsNumber: true })}
                  placeholder="1"
                  error={errors.min_quantity?.message}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Maximum Quantity
                </label>
                <Input
                  type="number"
                  step="1"
                  min="1"
                  {...register('max_quantity', {
                    valueAsNumber: true,
                    setValueAs: (v) => v === '' ? undefined : v
                  })}
                  placeholder="Leave blank for no limit"
                  error={errors.max_quantity?.message}
                />
                <p className="text-xs text-gray-500 mt-1">Leave blank for no limit</p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Effective From *
                </label>
                <Input
                  type="date"
                  {...register('effective_from')}
                  error={errors.effective_from?.message}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Effective To
                </label>
                <Input
                  type="date"
                  {...register('effective_to')}
                  placeholder="Leave blank for ongoing"
                  error={errors.effective_to?.message}
                />
                <p className="text-xs text-gray-500 mt-1">Leave blank for ongoing price</p>
              </div>

              <div>
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    {...register('active')}
                    className="w-4 h-4 rounded border-gray-300"
                  />
                  <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Active</span>
                </label>
              </div>
            </div>

            <div className="flex justify-end gap-4 pt-4 border-t">
              <Button
                type="button"
                variant="outline"
                onClick={() => router.back()}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                variant="primary"
                disabled={isSubmitting}
                loading={isSubmitting}
              >
                Update Product Price
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}

