/**
 * Edit Price List Page
 * Edit an existing price list
 */

'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 { pricingAPI } from '@/lib/api/pricing';
import { Button, Card, CardHeader, CardTitle, CardContent, Input, LoadingPage } from '@/components/ui';
import { ArrowLeft } from 'lucide-react';
import toast from 'react-hot-toast';

const priceListSchema = z.object({
  name: z.string().min(1, 'Name is required'),
  code: z.string().min(1, 'Code is required'),
  price_list_type: z.enum(['RETAIL', 'WHOLESALE', 'B2B', 'CUSTOMER_SPECIFIC']),
  currency: z.string().min(1, 'Currency is required'),
  description: z.string().optional(),
  is_default: z.boolean().default(false),
  active: z.boolean().default(true),
});

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

  // Fetch price list details
  const { data: priceList, isLoading, error } = 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),
  });

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm({
    resolver: zodResolver(priceListSchema),
    defaultValues: {
      name: '',
      code: '',
      price_list_type: 'RETAIL',
      currency: 'KES',
      description: '',
      is_default: false,
      active: true,
    },
  });

  // Update form when price list data loads
  useEffect(() => {
    if (priceList) {
      reset({
        name: priceList.name || '',
        code: priceList.code || '',
        price_list_type: priceList.price_list_type || 'RETAIL',
        currency: priceList.currency || 'KES',
        description: priceList.description || '',
        is_default: priceList.is_default || false,
        active: priceList.active !== undefined ? priceList.active : true,
      });
    }
  }, [priceList, reset]);

  const updatePriceListMutation = useMutation({
    mutationFn: async (data) => {
      return await pricingAPI.updatePriceList(priceListId, data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['price-list', priceListId]);
      queryClient.invalidateQueries(['price-lists']);
      toast.success('Price list updated successfully!');
      router.push(`/pricing/price-lists/${priceListId}`);
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to update price list';
      toast.error(message);
    },
    onSettled: () => {
      setIsSubmitting(false);
    },
  });

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

  if (isLoading) {
    return <LoadingPage message="Loading price list 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 (!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 Details
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Edit Price List</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">
                  Name *
                </label>
                <Input
                  {...register('name')}
                  placeholder="e.g., Retail Price List"
                  error={errors.name?.message}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Code *
                </label>
                <Input
                  {...register('code')}
                  placeholder="e.g., RETAIL"
                  error={errors.code?.message}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Type *
                </label>
                <select
                  {...register('price_list_type')}
                  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.price_list_type?.message}
                >
                  <option value="RETAIL">Retail</option>
                  <option value="WHOLESALE">Wholesale</option>
                  <option value="B2B">B2B</option>
                  <option value="CUSTOMER_SPECIFIC">Customer Specific</option>
                </select>
                {errors.price_list_type && (
                  <p className="text-sm text-red-600 mt-1">{errors.price_list_type.message}</p>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Currency *
                </label>
                <Input
                  {...register('currency')}
                  placeholder="KES"
                  maxLength={3}
                  error={errors.currency?.message}
                />
              </div>

              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Description
                </label>
                <textarea
                  {...register('description')}
                  rows={3}
                  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"
                  placeholder="Optional description"
                />
              </div>

              <div>
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    {...register('is_default')}
                    className="w-4 h-4 rounded border-gray-300"
                  />
                  <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Default Price List</span>
                </label>
              </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}
              >
                Save Changes
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}

