/**
 * New Discount Page
 * Create a new discount
 */

'use client';

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

const discountSchema = z.object({
  name: z.string().min(1, 'Name is required'),
  code: z.string().optional(),
  discount_type: z.enum(['PERCENTAGE', 'FIXED_AMOUNT', 'BUY_X_GET_Y'], {
    required_error: 'Discount type is required',
  }),
  discount_value: z.preprocess(
    (val) => (val === '' || val === null || val === undefined ? undefined : Number(val)),
    z.number({ invalid_type_error: 'Discount value must be a number' }).positive('Discount value must be positive')
  ),
  min_purchase_amount: z.preprocess(
    (val) => (val === '' || val === null || val === undefined ? 0 : Number(val)),
    z.number().nonnegative()
  ),
  max_discount_amount: z.preprocess(
    (val) => (val === '' || val === null || val === undefined ? null : Number(val)),
    z.number().nonnegative().nullable().optional()
  ),
  effective_from: z.string().min(1, 'Effective from date is required'),
  effective_to: z.string().optional().nullable(),
  max_uses_per_customer: z.preprocess(
    (val) => (val === '' || val === null || val === undefined || isNaN(Number(val)) ? null : Number(val)),
    z.number().int().positive().nullable().optional()
  ),
  max_total_uses: z.preprocess(
    (val) => (val === '' || val === null || val === undefined || isNaN(Number(val)) ? null : Number(val)),
    z.number().int().positive().nullable().optional()
  ),
  active: z.boolean().default(true),
  description: z.string().optional(),
  buy_quantity: z.preprocess(
    (val) => (val === '' || val === null || val === undefined || isNaN(Number(val)) ? null : Number(val)),
    z.number().int().positive().nullable().optional()
  ),
});

export default function NewDiscountPage() {
  const router = useRouter();
  const queryClient = useQueryClient();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(discountSchema),
    defaultValues: {
      name: '',
      code: '',
      discount_type: 'PERCENTAGE',
      discount_value: 1, // Changed from 0 to 1 to pass positive validation
      min_purchase_amount: 0,
      max_discount_amount: null,
      effective_from: new Date().toISOString().split('T')[0],
      effective_to: null,
      max_uses_per_customer: null,
      max_total_uses: null,
      active: true,
      description: '',
      buy_quantity: null,
    },
  });

  const discountType = watch('discount_type');

  const createDiscountMutation = useMutation({
    mutationFn: async (data) => {
      console.log('mutationFn called with data:', data);
      
      // Convert date strings to ISO 8601 format
      const formatDate = (dateString) => {
        if (!dateString) return null;
        // If it's already a full ISO string, return as is
        if (dateString.includes('T')) return dateString;
        // Convert YYYY-MM-DD to ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ)
        return new Date(dateString + 'T00:00:00.000Z').toISOString();
      };

      const discountData = {
        name: data.name,
        code: data.code && data.code.trim() ? data.code.trim() : null,
        discount_type: data.discount_type,
        discount_value: parseFloat(data.discount_value),
        min_purchase_amount: parseFloat(data.min_purchase_amount) || 0,
        max_discount_amount: data.max_discount_amount ? parseFloat(data.max_discount_amount) : null,
        effective_from: formatDate(data.effective_from),
        effective_to: formatDate(data.effective_to),
        max_uses_per_customer: data.max_uses_per_customer ? parseInt(data.max_uses_per_customer) : null,
        max_total_uses: data.max_total_uses ? parseInt(data.max_total_uses) : null,
        active: data.active !== false,
        description: data.description && data.description.trim() ? data.description.trim() : null,
        ...(data.discount_type === 'BUY_X_GET_Y' && data.buy_quantity && { buy_quantity: parseInt(data.buy_quantity) }),
      };
      
      console.log('Sending discountData to API:', discountData);
      const result = await discountsAPI.create(discountData);
      console.log('API response:', result);
      return result;
    },
    onSuccess: (data) => {
      console.log('Mutation onSuccess:', data);
      queryClient.invalidateQueries(['discounts']);
      toast.success('Discount created successfully!');
      router.push('/discounts');
    },
    onError: (error) => {
      console.error('Mutation onError:', error);
      console.error('Error details:', {
        message: error?.message,
        response: error?.response,
        responseData: error?.response?.data,
        errors: error?.response?.data?.errors,
      });
      const message = error?.response?.data?.message || error?.message || 'Failed to create discount';
      const errors = error?.response?.data?.errors;
      if (errors && Array.isArray(errors) && errors.length > 0) {
        toast.error(`${message}: ${errors.map(e => e.message || e.field).join(', ')}`);
      } else {
        toast.error(message);
      }
    },
  });

  const onSubmit = async (data) => {
    console.log('Form submitted with data:', data);
    
    // Additional validation based on discount type
    if (data.discount_type === 'PERCENTAGE' && (data.discount_value < 0 || data.discount_value > 100)) {
      toast.error('Percentage discount must be between 0 and 100');
      return;
    }

    if (data.discount_type === 'BUY_X_GET_Y' && !data.buy_quantity) {
      toast.error('Buy quantity is required for Buy X Get Y discounts');
      return;
    }

    setIsSubmitting(true);
    try {
      console.log('Calling createDiscountMutation...');
      const result = await createDiscountMutation.mutateAsync(data);
      console.log('Mutation result:', result);
    } catch (error) {
      console.error('Error in onSubmit:', error);
      // Error handled in mutation, but log for debugging
      if (!error.response) {
        toast.error('Network error. Please check your connection.');
      }
    } 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={() => router.push('/discounts')}
          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 Discount</h1>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Create a new discount or promotion
          </p>
        </div>
      </div>

      {/* Form */}
      <Card>
        <CardHeader>
          <CardTitle>Discount Information</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <Input
                  label="Discount Name"
                  {...register('name')}
                  error={errors.name?.message}
                  required
                  placeholder="e.g., Summer Sale"
                />
              </div>

              <div>
                <Input
                  label="Discount Code (Optional)"
                  {...register('code')}
                  error={errors.code?.message}
                  placeholder="e.g., SUMMER2024"
                />
                <p className="mt-1 text-xs text-gray-500">
                  Unique code for customers to use (auto-generated if left empty)
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Discount Type <span className="text-red-500">*</span>
                </label>
                <select
                  {...register('discount_type')}
                  className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                    errors.discount_type ? 'border-red-500' : 'border-gray-300'
                  }`}
                >
                  <option value="PERCENTAGE">Percentage</option>
                  <option value="FIXED_AMOUNT">Fixed Amount</option>
                  <option value="BUY_X_GET_Y">Buy X Get Y</option>
                </select>
                {errors.discount_type && (
                  <p className="mt-1 text-sm text-red-600">{errors.discount_type.message}</p>
                )}
              </div>

              {discountType === 'PERCENTAGE' && (
                <>
                  <div>
                    <Input
                      label="Discount Percentage (%)"
                      type="number"
                      step="0.01"
                      min="0"
                      max="100"
                      {...register('discount_value', { valueAsNumber: true })}
                      error={errors.discount_value?.message}
                      required
                      placeholder="10"
                    />
                  </div>
                  <div>
                    <Input
                      label="Maximum Discount Amount (Optional)"
                      type="number"
                      step="0.01"
                      min="0"
                      {...register('max_discount_amount', { valueAsNumber: true })}
                      error={errors.max_discount_amount?.message}
                      placeholder="1000"
                    />
                    <p className="mt-1 text-xs text-gray-500">
                      Cap the discount amount (leave empty for no limit)
                    </p>
                  </div>
                </>
              )}

              {discountType === 'FIXED_AMOUNT' && (
                <div>
                  <Input
                    label="Discount Amount"
                    type="number"
                    step="0.01"
                    min="0.01"
                    {...register('discount_value', { valueAsNumber: true })}
                    error={errors.discount_value?.message}
                    required
                    placeholder="50"
                  />
                </div>
              )}

              {discountType === 'BUY_X_GET_Y' && (
                <>
                  <div>
                    <Input
                      label="Buy Quantity (X)"
                      type="number"
                      step="1"
                      min="1"
                      {...register('buy_quantity', { valueAsNumber: true })}
                      error={errors.buy_quantity?.message}
                      required
                      placeholder="2"
                    />
                  </div>
                  <div>
                    <Input
                      label="Get Quantity (Y)"
                      type="number"
                      step="1"
                      min="1"
                      {...register('discount_value', { valueAsNumber: true })}
                      error={errors.discount_value?.message}
                      required
                      placeholder="1"
                    />
                    <p className="mt-1 text-xs text-gray-500">
                      Number of items to get for free
                    </p>
                  </div>
                </>
              )}

              <div>
                <Input
                  label="Minimum Purchase Amount"
                  type="number"
                  step="0.01"
                  min="0"
                  {...register('min_purchase_amount', { valueAsNumber: true })}
                  error={errors.min_purchase_amount?.message}
                  defaultValue={0}
                  placeholder="0"
                />
              </div>

              <div>
                <Input
                  label="Effective From"
                  type="date"
                  {...register('effective_from')}
                  error={errors.effective_from?.message}
                  required
                  defaultValue={new Date().toISOString().split('T')[0]}
                />
              </div>

              <div>
                <Input
                  label="Effective To (Optional)"
                  type="date"
                  {...register('effective_to')}
                  error={errors.effective_to?.message}
                />
                <p className="mt-1 text-xs text-gray-500">
                  Leave empty for no expiration
                </p>
              </div>

              <div>
                <Input
                  label="Max Uses Per Customer (Optional)"
                  type="number"
                  step="1"
                  min="1"
                  {...register('max_uses_per_customer', { valueAsNumber: true })}
                  error={errors.max_uses_per_customer?.message}
                  placeholder="Unlimited"
                />
              </div>

              <div>
                <Input
                  label="Max Total Uses (Optional)"
                  type="number"
                  step="1"
                  min="1"
                  {...register('max_total_uses', { valueAsNumber: true })}
                  error={errors.max_total_uses?.message}
                  placeholder="Unlimited"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Description (Optional)
              </label>
              <textarea
                {...register('description')}
                rows={4}
                className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                  errors.description ? 'border-red-500' : 'border-gray-300'
                }`}
                placeholder="Discount description..."
              />
            </div>

            <div className="flex items-center">
              <input
                type="checkbox"
                {...register('active')}
                defaultChecked
                className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
              />
              <label className="ml-2 text-sm font-medium text-gray-700">
                Active (discount is currently available)
              </label>
            </div>

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

