/**
 * New Product Page
 * Create a new product
 */

'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query';
import { productsAPI } from '@/lib/api/products';
import { categoriesAPI } from '@/lib/api/categories';
import { Button, Card, CardHeader, CardTitle, CardContent, Input, Textarea, Select } from '@/components/ui';
import { PRODUCT_TYPES } from '@/lib/utils/constants';
import { ArrowLeft } from 'lucide-react';
import toast from 'react-hot-toast';

const productSchema = z.object({
  name: z.string().min(1, 'Product name is required').max(150, 'Product name must not exceed 150 characters'),
  sku: z.string().optional(),
  product_type: z.enum(['FG', 'RM'], { required_error: 'Product type is required' }),
  track_inventory: z.boolean().default(true),
  track_by_dimensions: z.boolean().optional(),
  unit_of_measure: z.enum(['inch', 'cm', 'm']).nullable().optional(),
  description: z.string().optional(),
  selling_price: z.number().min(0, 'Selling price must be non-negative').optional().or(z.literal('')),
  category_ids: z.array(z.number()).optional(),
  primary_category_id: z.number().optional().or(z.literal('')),
}).refine((data) => {
  // If RM product, track_by_dimensions must be set
  if (data.product_type === 'RM') {
    return data.track_by_dimensions !== undefined;
  }
  return true;
}, {
  message: 'Track by dimensions must be set for RM products',
  path: ['track_by_dimensions'],
}).refine((data) => {
  // If dimension-based RM, unit_of_measure is required
  if (data.product_type === 'RM' && data.track_by_dimensions === true) {
    return data.unit_of_measure !== null && data.unit_of_measure !== undefined;
  }
  return true;
}, {
  message: 'Unit of measure is required for dimension-based RM products',
  path: ['unit_of_measure'],
});

export default function NewProductPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const queryClient = useQueryClient();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [selectedCategoryId, setSelectedCategoryId] = useState('');

  // Get product type from URL query parameter
  const typeFromUrl = searchParams?.get('type')?.toUpperCase();
  const defaultProductType = (typeFromUrl === 'FG' || typeFromUrl === 'RM') ? typeFromUrl : 'FG';

  // Fetch categories for selection
  const { data: categoriesData, isLoading: categoriesLoading, error: categoriesError } = useQuery({
    queryKey: ['categories', 'all'],
    queryFn: async () => {
      try {
        // API has max limit of 100, fetch with max allowed
        const response = await categoriesAPI.list({ limit: 100, page: 1 });
        
        // API interceptor returns response.data from axios
        // Server returns: { success: true, message: "...", data: { categories: [...], pagination: {...} } }
        // After interceptor: response = { success: true, message: "...", data: { categories: [...], pagination: {...} } }
        // Categories page uses: response.data || response, then data?.categories
        // So we should use the same pattern
        const data = response?.data || response;
        const categories = data?.categories || [];
        
        // Debug log in development
        if (process.env.NODE_ENV === 'development') {
          console.log('Categories API response:', { 
            rawResponse: response, 
            responseType: typeof response,
            hasData: !!response?.data,
            hasCategories: !!response?.data?.categories,
            categories, 
            count: categories?.length,
            firstCategory: categories?.[0] 
          });
        }
        
        return Array.isArray(categories) ? categories : [];
      } catch (error) {
        console.error('Error fetching categories:', error);
        return [];
      }
    },
  });

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(productSchema),
    defaultValues: {
      track_inventory: true,
      product_type: defaultProductType,
      track_by_dimensions: defaultProductType === 'RM' ? true : undefined, // Default to true for RM products (dimension-based)
    },
  });

  // Set product type from URL if provided
  useEffect(() => {
    if (typeFromUrl && (typeFromUrl === 'FG' || typeFromUrl === 'RM')) {
      setValue('product_type', typeFromUrl);
      if (typeFromUrl === 'RM') {
        setValue('track_by_dimensions', true);
      }
    }
  }, [typeFromUrl, setValue]);

  const productType = watch('product_type');
  const trackByDimensions = watch('track_by_dimensions');
  const isRM = productType === 'RM';
  const isDimensionBasedRM = isRM && trackByDimensions === true;

  // Reset RM-specific fields when product type changes
  useEffect(() => {
    if (productType !== 'RM') {
      setValue('track_by_dimensions', undefined);
      setValue('unit_of_measure', undefined);
    } else if (productType === 'RM' && trackByDimensions === undefined) {
      // Default to dimension-based for new RM products
      setValue('track_by_dimensions', true);
    }
  }, [productType, setValue]);

  const createProductMutation = useMutation({
    mutationFn: async (data) => {
      const productData = {
        ...data,
        selling_price: data.selling_price === '' ? undefined : data.selling_price,
        // Handle track_by_dimensions and unit_of_measure for RM products
        track_by_dimensions: data.product_type === 'RM' ? (data.track_by_dimensions ?? true) : undefined,
        unit_of_measure: data.product_type === 'RM' && data.track_by_dimensions === true 
          ? data.unit_of_measure 
          : (data.product_type === 'RM' && data.track_by_dimensions === false ? null : undefined),
      };
      // Remove category fields from product data (handled separately)
      delete productData.category_ids;
      delete productData.primary_category_id;
      
      // Create product first
      const result = await productsAPI.create(productData);
      
      // Then assign category if selected
      if (selectedCategoryId) {
        await categoriesAPI.assignProductToCategories(
          result.data.product.id,
          [parseInt(selectedCategoryId)],
          parseInt(selectedCategoryId) // Same category is primary
        );
      }
      
      return result;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries(['products']);
      toast.success('Product created successfully!');
      // Navigate to appropriate page based on product type
      const productType = data?.data?.product?.product_type || 'FG';
      if (productType === 'RM') {
        router.push('/products/raw-materials');
      } else {
        router.push('/products/finished-goods');
      }
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to create product';
      toast.error(message);
    },
  });

  const onSubmit = async (data) => {
    setIsSubmitting(true);
    try {
      await createProductMutation.mutateAsync(data);
    } catch (error) {
      // Error handled in mutation
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-950 space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button
          variant="outline"
          onClick={() => {
            // Navigate back to appropriate page based on product type
            if (productType === 'RM') {
              router.push('/products/raw-materials');
            } else {
              router.push('/products/finished-goods');
            }
          }}
          className="flex items-center gap-2"
        >
          <ArrowLeft className="w-4 h-4" />
          Back
        </Button>
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
            New {productType === 'RM' ? 'Raw Material' : 'Finished Good'}
          </h1>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Create a new {productType === 'RM' ? 'raw material' : 'finished good'}
          </p>
        </div>
      </div>

      {/* Form */}
      <Card>
        <CardHeader>
          <CardTitle>Product Information</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <Input
                label="Product Name"
                type="text"
                placeholder="Enter product name"
                {...register('name')}
                error={errors.name?.message}
                required
                autoFocus
              />

              <Input
                label="SKU"
                type="text"
                placeholder="Enter SKU (optional)"
                {...register('sku')}
                error={errors.sku?.message}
              />

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Product Type <span className="text-red-500">*</span>
                </label>
                <select
                  {...register('product_type')}
                  className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:text-white dark:border-gray-700 ${
                    errors.product_type ? 'border-red-500' : 'border-gray-300 dark:border-gray-700'
                  }`}
                  required
                >
                  <option value="">Select type</option>
                  <option value="FG">Finished Goods</option>
                  <option value="RM">Raw Materials</option>
                </select>
                {errors.product_type && (
                  <p className="mt-1 text-sm text-red-600">{errors.product_type.message}</p>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Track Inventory
                </label>
                <input
                  type="checkbox"
                  {...register('track_inventory')}
                  className="w-4 h-4 text-blue-600 border-gray-300 dark:border-gray-600 rounded focus:ring-blue-500 dark:bg-gray-800 dark:checked:bg-blue-600"
                />
              </div>

              {/* RM-specific fields */}
              {isRM && (
                <>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Track by Dimensions
                      <span className="text-red-500 ml-1">*</span>
                    </label>
                    <div className="flex items-center gap-2">
                      <input
                        type="checkbox"
                        {...register('track_by_dimensions')}
                        checked={trackByDimensions ?? true}
                        onChange={(e) => {
                          setValue('track_by_dimensions', e.target.checked);
                          if (!e.target.checked) {
                            setValue('unit_of_measure', null);
                          }
                        }}
                        className="w-4 h-4 text-blue-600 border-gray-300 dark:border-gray-600 rounded focus:ring-blue-500 dark:bg-gray-800 dark:checked:bg-blue-600"
                      />
                      <span className="text-sm text-gray-600 dark:text-gray-400">
                        {trackByDimensions ? 'Dimension-based (fabric, leather)' : 'Special items (zippers, buttons)'}
                      </span>
                    </div>
                    <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                      {trackByDimensions 
                        ? 'Track materials by length × width dimensions'
                        : 'Track materials by quantity (zippers, buttons, threads, etc.)'}
                    </p>
                    {errors.track_by_dimensions && (
                      <p className="mt-1 text-sm text-red-600">{errors.track_by_dimensions.message}</p>
                    )}
                  </div>

                  {isDimensionBasedRM && (
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        Unit of Measure
                        <span className="text-red-500 ml-1">*</span>
                      </label>
                      <select
                        {...register('unit_of_measure')}
                        className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:text-white dark:border-gray-700 ${
                          errors.unit_of_measure ? 'border-red-500' : 'border-gray-300 dark:border-gray-700'
                        }`}
                      >
                        <option value="">Select unit</option>
                        <option value="inch">Inches (in)</option>
                        <option value="cm">Centimeters (cm)</option>
                        <option value="m">Meters (m)</option>
                      </select>
                      {errors.unit_of_measure && (
                        <p className="mt-1 text-sm text-red-600">{errors.unit_of_measure.message}</p>
                      )}
                      <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Unit for length and width measurements
                      </p>
                    </div>
                  )}
                </>
              )}

              <Input
                label="Selling Price"
                type="number"
                step="0.01"
                min="0"
                placeholder="e.g., 100.00"
                {...register('selling_price', { valueAsNumber: true })}
                error={errors.selling_price?.message}
              />
              <div className="text-xs text-gray-500 dark:text-gray-400">
                Simple default price. Can be overridden by price lists.
              </div>

              {/* Category Selection */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Category
                </label>
                <select
                  value={selectedCategoryId}
                  onChange={(e) => setSelectedCategoryId(e.target.value)}
                  className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-800 dark:text-white ${
                    categoriesLoading ? 'opacity-50' : ''
                  } border-gray-300 dark:border-gray-700`}
                  disabled={categoriesLoading}
                >
                  <option value="">Select a category (optional)</option>
                  {categoriesData?.map((category) => (
                    <option key={category.id} value={category.id}>
                      {category.name}
                    </option>
                  ))}
                </select>
                {categoriesLoading && (
                  <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">Loading categories...</p>
                )}
                {categoriesError && (
                  <p className="mt-1 text-xs text-red-600 dark:text-red-400">
                    Error loading categories: {categoriesError.message}
                  </p>
                )}
                {!categoriesLoading && !categoriesError && categoriesData?.length === 0 && (
                  <p className="mt-1 text-xs text-amber-600 dark:text-amber-400">
                    No categories available. <a href="/categories/new" className="underline">Create one</a>
                  </p>
                )}
                {!categoriesLoading && categoriesData && categoriesData.length > 0 && (
                  <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    {categoriesData.length} categor{categoriesData.length === 1 ? 'y' : 'ies'} available. Assign this product to a category for better organization.
                  </p>
                )}
              </div>
            </div>

            <Textarea
              label="Description"
              placeholder="Enter product description (optional)"
              rows={4}
              {...register('description')}
              error={errors.description?.message}
            />

            <div className="flex justify-end gap-4 pt-4 border-t dark:border-gray-700">
              <Button
                type="button"
                variant="outline"
                onClick={() => {
                  // Navigate back to appropriate page based on product type
                  if (productType === 'RM') {
                    router.push('/products/raw-materials');
                  } else {
                    router.push('/products/finished-goods');
                  }
                }}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                variant="primary"
                disabled={isSubmitting}
                loading={isSubmitting}
              >
                Create Product
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}

