/**
 * New Product Price Page
 * Add a product price to a price list
 */

'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter, useSearchParams } 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({
  product_id: z.number().int().positive('Product is required'),
  variant_id: z.preprocess(
    (val) => (val === '' || val === null || val === undefined ? undefined : val),
    z.number().int().positive().optional()
  ),
  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.preprocess(
    (val) => (val === '' || val === null || val === undefined ? undefined : val),
    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 NewProductPricePage() {
  const router = useRouter();
  const params = useParams();
  const searchParams = useSearchParams();
  const priceListId = parseInt(params.id);
  const queryClient = useQueryClient();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [selectedProductId, setSelectedProductId] = useState(null);

  // Fetch price list details
  const { data: priceList, isLoading: isLoadingPriceList } = 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 products
  const { data: productsData } = useQuery({
    queryKey: ['products', 'all'],
    queryFn: async () => {
      const response = await productsAPI.list({ limit: 100 });
      return response?.data || response;
    },
  });

  const products = productsData?.products || [];
  const selectedProduct = products.find(p => p.id === selectedProductId);
  const variants = selectedProduct?.variants || [];

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

  const watchedProductId = watch('product_id');

  // Update selected product when form value changes
  useEffect(() => {
    const productId = typeof watchedProductId === 'string' ? parseInt(watchedProductId) : watchedProductId;
    setSelectedProductId(productId || null);
    // Reset variant when product changes
    if (productId) {
      setValue('variant_id', undefined);
    }
  }, [watchedProductId, setValue]);

  // Set initial product from URL params
  useEffect(() => {
    const productId = searchParams.get('product_id');
    if (productId) {
      const parsedProductId = parseInt(productId);
      setValue('product_id', parsedProductId);
      setSelectedProductId(parsedProductId);
    }
  }, [searchParams, setValue]);

  const createProductPriceMutation = useMutation({
    mutationFn: async (data) => {
      const priceData = {
        price_list_id: priceListId,
        product_id: data.product_id,
        price: parseFloat(data.price),
        min_quantity: parseFloat(data.min_quantity) || 1,
        max_quantity: data.max_quantity !== undefined && data.max_quantity !== null && 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,
        // Always include variant_id - set to null if not provided
        variant_id: data.variant_id !== undefined && data.variant_id !== null && data.variant_id !== '' 
          ? parseInt(data.variant_id) 
          : null,
      };
      return await pricingAPI.createProductPrice(priceData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['product-prices', priceListId]);
      queryClient.invalidateQueries(['price-list', priceListId]);
      toast.success('Product price created successfully!');
      router.push(`/pricing/price-lists/${priceListId}`);
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to create product price';
      toast.error(message);
    },
    onSettled: () => {
      setIsSubmitting(false);
    },
  });

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

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

  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-4xl">
      <div className="mb-6">
        <Button variant="ghost" onClick={() => router.back()} className="flex items-center">
          <ArrowLeft className="w-4 h-4 mr-2" /> Back to Price List
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Add Product Price to {priceList.name}</CardTitle>
        </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">
                  Product *
                </label>
                <select
                  {...register('product_id', { valueAsNumber: true })}
                  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"
                  error={errors.product_id?.message}
                >
                  <option value="0">Select a product</option>
                  {products.map((product) => (
                    <option key={product.id} value={product.id}>
                      {product.name} ({product.sku})
                    </option>
                  ))}
                </select>
                {errors.product_id && (
                  <p className="text-sm text-red-600 mt-1">{errors.product_id.message}</p>
                )}
              </div>

              {selectedProduct && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Variant (Optional)
                  </label>
                  {variants.length > 0 ? (
                    <select
                      {...register('variant_id', {
                        setValueAs: (v) => v === '' ? undefined : (v ? parseInt(v) : undefined),
                      })}
                      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"
                      error={errors.variant_id?.message}
                    >
                      <option value="">Standard (No Variant)</option>
                      {variants.map((variant) => (
                        <option key={variant.id} value={variant.id}>
                          {variant.name} {variant.sku ? `(${variant.sku})` : ''}
                        </option>
                      ))}
                    </select>
                  ) : (
                    <input
                      type="text"
                      value="Standard (No Variants Available)"
                      disabled
                      className="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-100 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-400 cursor-not-allowed"
                    />
                  )}
                  {errors.variant_id && (
                    <p className="text-sm text-red-600 mt-1">{errors.variant_id.message}</p>
                  )}
                  <p className="text-xs text-gray-500 mt-1">Select a variant if this price applies to a specific variant, or leave as "Standard" for base product pricing</p>
                </div>
              )}

              <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}
              >
                Add Product Price
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}

