/**
 * Edit Discount Page
 * Edit an existing discount
 */

'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 { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { discountsAPI } from '@/lib/api/discounts';
import { Button, Card, CardHeader, CardTitle, CardContent, Input, LoadingPage } 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 EditDiscountPage() {
  const router = useRouter();
  const params = useParams();
  const discountId = parseInt(params.id);
  const queryClient = useQueryClient();
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Fetch discount details
  const { data: discount, isLoading, error } = useQuery({
    queryKey: ['discount', discountId],
    queryFn: async () => {
      if (isNaN(discountId)) {
        throw new Error('Invalid discount ID');
      }
      const response = await discountsAPI.getById(discountId);
      return response?.data || response;
    },
    enabled: !isNaN(discountId),
  });

  const {
    register,
    handleSubmit,
    watch,
    reset,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(discountSchema),
  });

  // Reset form when discount data is loaded
  useEffect(() => {
    if (discount) {
      reset({
        name: discount.name || '',
        code: discount.code || '',
        discount_type: discount.discount_type || 'PERCENTAGE',
        discount_value: discount.discount_value || 0,
        min_purchase_amount: discount.min_purchase_amount || 0,
        max_discount_amount: discount.max_discount_amount || null,
        effective_from: discount.effective_from
          ? new Date(discount.effective_from).toISOString().split('T')[0]
          : new Date().toISOString().split('T')[0],
        effective_to: discount.effective_to
          ? new Date(discount.effective_to).toISOString().split('T')[0]
          : null,
        max_uses_per_customer: discount.max_uses_per_customer || null,
        max_total_uses: discount.max_total_uses || null,
        active: discount.active !== false,
        description: discount.description || '',
        buy_quantity: discount.buy_quantity || null,
      });
    }
  }, [discount, reset]);

  const discountType = watch('discount_type');

  const updateDiscountMutation = 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.update(discountId, discountData);
      console.log('API response:', result);
      return result;
    },
    onSuccess: (data) => {
      console.log('Mutation onSuccess:', data);
      queryClient.invalidateQueries(['discount', discountId]);
      queryClient.invalidateQueries(['discounts']);
      toast.success('Discount updated successfully!');
      router.push(`/discounts/${discountId}`);
    },
    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 update 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);
    
    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 updateDiscountMutation...');
      const result = await updateDiscountMutation.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);
    }
  };

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

  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/${discountId}`)}
          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">Edit Discount</h1>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Update discount information
          </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
                />
              </div>

              <div>
                <Input
                  label="Discount Code (Optional)"
                  {...register('code')}
                  error={errors.code?.message}
                />
              </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
                    />
                  </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}
                    />
                  </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
                  />
                </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
                    />
                  </div>
                  <div>
                    <Input
                      label="Get Quantity (Y)"
                      type="number"
                      step="1"
                      min="1"
                      {...register('discount_value', { valueAsNumber: true })}
                      error={errors.discount_value?.message}
                      required
                    />
                  </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}
                />
              </div>

              <div>
                <Input
                  label="Effective From"
                  type="date"
                  {...register('effective_from')}
                  error={errors.effective_from?.message}
                  required
                />
              </div>

              <div>
                <Input
                  label="Effective To (Optional)"
                  type="date"
                  {...register('effective_to')}
                  error={errors.effective_to?.message}
                />
              </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}
                />
              </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}
                />
              </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')}
                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/${discountId}`)}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button type="submit" variant="primary" disabled={isSubmitting} loading={isSubmitting}>
                Update Discount
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}

