import { useState } from 'react';
import { useLocation } from 'wouter';
import { useMutation } from '@tanstack/react-query';
import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { queryClient, apiRequest } from '@/lib/queryClient';
import { useToast } from '@/hooks/use-toast';
import { PageLayout } from '@/components/layout/PageLayout';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { Loader2 } from 'lucide-react';

// Form validation schema
const createCollectionSchema = z.object({
  name: z.string().min(3, { message: 'Collection name must be at least 3 characters' }).max(100),
  description: z.string().max(500, { message: 'Description must not exceed 500 characters' }).optional(),
  isPublic: z.boolean().default(true),
});

type FormValues = z.infer<typeof createCollectionSchema>;

export default function CreateCollection() {
  const [, navigate] = useLocation();
  const { toast } = useToast();
  
  // Initialize form
  const form = useForm<FormValues>({
    resolver: zodResolver(createCollectionSchema),
    defaultValues: {
      name: '',
      description: '',
      isPublic: true,
    },
  });
  
  // Create collection mutation
  const createMutation = useMutation({
    mutationFn: async (values: FormValues) => {
      return await apiRequest('POST', '/api/collections', {
        name: values.name,
        description: values.description || '',
        isPublic: values.isPublic,
        userId: 1, // Using mock user ID for demo purposes
      });
    },
    onSuccess: (data) => {
      toast({
        title: 'Collection created',
        description: 'Your collection has been created successfully',
      });
      queryClient.invalidateQueries({ queryKey: ['/api/collections'] });
      navigate(`/collections`);
    },
    onError: (error) => {
      toast({
        title: 'Error',
        description: `Failed to create collection: ${error.message}`,
        variant: 'destructive',
      });
    },
  });
  
  const onSubmit = (values: FormValues) => {
    createMutation.mutate(values);
  };
  
  return (
    <PageLayout>
      <div className="max-w-3xl mx-auto py-8 px-4 md:px-6">
        <div className="mb-8">
          <h1 className="text-2xl md:text-3xl font-bold font-serif text-navy dark:text-cream mb-2">
            Create a Collection
          </h1>
          <p className="text-navy/70 dark:text-cream/70">
            Collections help you organize literary works into themed groups that you can share with others.
          </p>
        </div>
        
        <div className="bg-cream dark:bg-dark-surface p-6 rounded-lg shadow-sm border border-sage/10 dark:border-sage/5">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Collection Name</FormLabel>
                    <FormControl>
                      <Input placeholder="Enter collection name" {...field} />
                    </FormControl>
                    <FormDescription>
                      Choose a descriptive name for your collection
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
              
              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Description</FormLabel>
                    <FormControl>
                      <Textarea 
                        placeholder="Describe what this collection is about" 
                        className="min-h-24 resize-y"
                        {...field} 
                      />
                    </FormControl>
                    <FormDescription>
                      Provide a brief description of your collection (optional)
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
              
              <FormField
                control={form.control}
                name="isPublic"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-center justify-between rounded-lg border border-sage/10 dark:border-sage/5 p-4">
                    <div className="space-y-0.5">
                      <FormLabel className="text-base">Public Collection</FormLabel>
                      <FormDescription>
                        When enabled, your collection will be visible to all users.
                        <br />
                        Private collections are only visible to you.
                      </FormDescription>
                    </div>
                    <FormControl>
                      <Switch
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                  </FormItem>
                )}
              />
              
              <div className="flex justify-end gap-4 pt-4">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => navigate('/collections')}
                >
                  Cancel
                </Button>
                <Button 
                  type="submit"
                  disabled={createMutation.isPending}
                >
                  {createMutation.isPending && (
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  )}
                  Create Collection
                </Button>
              </div>
            </form>
          </Form>
        </div>
      </div>
    </PageLayout>
  );
}