/**
 * Edit Category Page
 * Edit an existing category
 */

'use client';

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

const categorySchema = z.object({
  name: z.string().min(1, 'Category name is required').max(150, 'Category name must not exceed 150 characters'),
  parent_id: z.number().optional().nullable().or(z.literal('')),
  description: z.string().optional(),
  slug: z.string().optional(),
  sort_order: z.number().optional(),
});

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

  // Fetch category data
  const { data: category, isLoading } = useQuery({
    queryKey: ['category', categoryId],
    queryFn: async () => {
      const response = await categoriesAPI.getById(categoryId);
      return response?.data || null;
    },
  });

  // Fetch all categories for parent selection (exclude current category to prevent circular reference)
  const { data: categoriesData } = useQuery({
    queryKey: ['categories', 'all'],
    queryFn: async () => {
      const response = await categoriesAPI.list({ limit: 1000 });
      return response?.data?.categories || [];
    },
  });

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(categorySchema),
    values: category ? {
      name: category.name || '',
      parent_id: category.parent_id || '',
      description: category.description || '',
      slug: category.slug || '',
      sort_order: category.sort_order || 0,
    } : undefined,
  });

  const updateCategoryMutation = useMutation({
    mutationFn: async (data) => {
      const categoryData = {
        ...data,
        parent_id: data.parent_id === '' ? null : data.parent_id,
        description: data.description === '' ? undefined : data.description,
        slug: data.slug === '' ? undefined : data.slug,
      };
      return await categoriesAPI.update(categoryId, categoryData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['category', categoryId]);
      queryClient.invalidateQueries(['categories']);
      toast.success('Category updated successfully!');
      router.push(`/categories/${categoryId}`);
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to update category';
      toast.error(message);
    },
  });

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

  if (isLoading) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950">
        <div className="flex justify-center py-12">
          <LoadingSpinner size="lg" />
        </div>
      </div>
    );
  }

  if (!category) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950">
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-12">
              <p className="text-red-600 dark:text-red-400 mb-4">Category not found</p>
              <Button onClick={() => router.push('/categories')} variant="outline">
                Back to Categories
              </Button>
            </div>
          </CardContent>
        </Card>
      </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(`/categories/${categoryId}`)}
          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 Category</h1>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            {category.name}
          </p>
        </div>
      </div>

      {/* Form */}
      <Card>
        <CardHeader>
          <CardTitle>Category 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="Category Name"
                type="text"
                placeholder="Enter category name"
                {...register('name')}
                error={errors.name?.message}
                required
              />

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Parent Category
                </label>
                <select
                  {...register('parent_id', {
                    setValueAs: (value) => value === '' ? null : parseInt(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 ${
                    errors.parent_id ? 'border-red-500' : 'border-gray-300 dark:border-gray-700'
                  }`}
                >
                  <option value="">None (Root Category)</option>
                  {categoriesData?.filter(cat => cat.id !== categoryId).map((category) => (
                    <option key={category.id} value={category.id}>
                      {category.name}
                    </option>
                  ))}
                </select>
                {errors.parent_id && (
                  <p className="mt-1 text-sm text-red-600">{errors.parent_id.message}</p>
                )}
                <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                  Select a parent category to create a subcategory. Leave empty for root category. Cannot select self.
                </p>
              </div>

              <Input
                label="Slug"
                type="text"
                placeholder="URL slug (optional)"
                {...register('slug')}
                error={errors.slug?.message}
              />

              <Input
                label="Sort Order"
                type="number"
                placeholder="0"
                {...register('sort_order', { valueAsNumber: true })}
                error={errors.sort_order?.message}
              />
            </div>

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

            <div className="flex justify-end gap-4 pt-4 border-t">
              <Button
                type="button"
                variant="outline"
                onClick={() => router.push(`/categories/${categoryId}`)}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                variant="primary"
                disabled={isSubmitting}
                loading={isSubmitting}
              >
                Update Category
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}

