import { zodResolver } from "@hookform/resolvers/zod";
import { createBlogPostSchema, type Tag } from "@shared/schema";
import { useMutation, useQuery } from "@tanstack/react-query";
import { ChevronLeft, Loader2 } from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { Link, useLocation } from "wouter";
import { z } from "zod";
import { BlogEditor } from "@/components/blog/blog-editor";
import { TagManager } from "@/components/blog/tag-manager";
import { PageLayout } from "@/components/layout/PageLayout";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { apiRequest, queryClient } from "@/lib/queryClient";

const blogPostSchema = createBlogPostSchema.extend({
  tags: z.array(z.number()).optional(),
});

type FormValues = z.infer<typeof blogPostSchema>;

export default function BlogCreate() {
  const [, navigate] = useLocation();
  const { toast } = useToast();
  const [publishNow, setPublishNow] = useState(true);

  // Fetch tags for selection
  const { data: tags } = useQuery<Tag[]>({
    queryKey: ["/api/tags"],
  });

  // Form definition
  const form = useForm<FormValues>({
    resolver: zodResolver(blogPostSchema),
    defaultValues: {
      title: "",
      content: "",
      excerpt: "", // Using empty string instead of null
      authorId: "",
      tags: [],
    },
  });

  // Create blog post mutation
  const createMutation = useMutation({
    mutationFn: async (values: FormValues) => {
      // If publishNow is true, set publishedAt to current date
      const postData = publishNow
        ? { ...values, publishedAt: new Date().toISOString() }
        : values;

      return await apiRequest("POST", "/api/blog", postData);
    },
    onSuccess: () => {
      toast({
        title: "Success",
        description: publishNow
          ? "Your article has been published"
          : "Your article has been saved as a draft",
      });

      // Invalidate queries to refresh the data
      queryClient.invalidateQueries({ queryKey: ["/api/blog"] });

      // Navigate to blog list
      navigate("/blog");
    },
    onError: (_error) => {
      toast({
        title: "Error",
        description: "Failed to create blog post",
        variant: "destructive",
      });
    },
  });

  // Handle form submission
  const onSubmit = (values: FormValues) => {
    createMutation.mutate(values);
  };

  return (
    <PageLayout>
      <div className="max-w-5xl mx-auto px-4 py-8">
        <div className="mb-6">
          <Link href="/blog">
            <Button
              variant="ghost"
              className="px-0 text-navy/70 dark:text-cream/70 hover:text-navy dark:hover:text-cream hover:bg-transparent"
            >
              <ChevronLeft className="h-4 w-4 mr-1" />
              Back to Blog
            </Button>
          </Link>

          <h1 className="text-3xl font-serif font-bold text-navy dark:text-cream mt-4">
            Write an Article
          </h1>
          <p className="text-navy/70 dark:text-cream/70 mt-1">
            Share your knowledge, insights, and perspectives on literature and
            translations
          </p>
        </div>

        <div className="bg-cream dark:bg-dark-surface rounded-lg border border-sage/20 dark:border-sage/10 p-6">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
              <FormField
                control={form.control}
                name="title"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Title</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter a descriptive title for your article"
                        className="text-lg font-medium"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="excerpt"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Excerpt (Summary)</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="Provide a short summary of your article (will appear in previews)"
                        className="resize-y h-20"
                        value={field.value || ""}
                        onChange={field.onChange}
                        onBlur={field.onBlur}
                        name={field.name}
                        ref={field.ref}
                      />
                    </FormControl>
                    <FormDescription>
                      A brief summary helps readers decide if they want to read
                      the full article.
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <TagManager name="tags" tags={tags} label="Tags" />

              <BlogEditor
                name="content"
                label="Content"
                placeholder="Write your article content here..."
              />

              <div className="flex items-center space-x-2">
                <Switch
                  id="publish-now"
                  checked={publishNow}
                  onCheckedChange={setPublishNow}
                />
                <Label htmlFor="publish-now">
                  {publishNow ? "Publish immediately" : "Save as draft"}
                </Label>
              </div>

              <div className="flex justify-end gap-3">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => navigate("/blog")}
                >
                  Cancel
                </Button>

                <Button
                  type="submit"
                  className="bg-russet hover:bg-russet/90"
                  disabled={createMutation.isPending}
                >
                  {createMutation.isPending && (
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  )}
                  {publishNow ? "Publish Article" : "Save Draft"}
                </Button>
              </div>
            </form>
          </Form>
        </div>
      </div>
    </PageLayout>
  );
}
