import { PageLayout } from "@/components/layout/PageLayout";
import { Button } from "@/components/ui/button";
import { Link, useLocation } from "wouter";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "@/components/ui/select";
import { ChevronLeft, Plus, X, Loader2 } from "lucide-react";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast";
import { insertBlogPostSchema, Tag } from "@shared/schema";

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

type FormValues = z.infer<typeof blogPostSchema>;

// Simple rich text editor toolbar
function EditorToolbar() {
  return (
    <div className="flex flex-wrap gap-1 mb-2 border-b border-sage/20 dark:border-sage/10 pb-2">
      <Button type="button" variant="ghost" size="sm" className="px-2 font-bold">
        B
      </Button>
      <Button type="button" variant="ghost" size="sm" className="px-2 italic">
        I
      </Button>
      <Button type="button" variant="ghost" size="sm" className="px-2 underline">
        U
      </Button>
      <Button type="button" variant="ghost" size="sm" className="px-2">
        H1
      </Button>
      <Button type="button" variant="ghost" size="sm" className="px-2">
        H2
      </Button>
      <Button type="button" variant="ghost" size="sm" className="px-3">
        • List
      </Button>
      <Button type="button" variant="ghost" size="sm" className="px-3">
        1. List
      </Button>
      <Button type="button" variant="ghost" size="sm" className="px-2">
        Link
      </Button>
      <Button type="button" variant="ghost" size="sm" className="px-2">
        Quote
      </Button>
      <Button type="button" variant="ghost" size="sm" className="px-2">
        Code
      </Button>
    </div>
  );
}

export default function BlogCreate() {
  const [, navigate] = useLocation();
  const { toast } = useToast();
  const [selectedTags, setSelectedTags] = useState<Tag[]>([]);
  const [selectedTagId, setSelectedTagId] = useState<string>("");
  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: 1, // Mock user ID for demo
      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 tag selection
  const handleAddTag = () => {
    if (!selectedTagId) return;
    
    const tagId = parseInt(selectedTagId, 10);
    const tag = tags?.find(t => t.id === tagId);
    
    if (tag && !selectedTags.some(t => t.id === tag.id)) {
      setSelectedTags([...selectedTags, tag]);
      
      // Update form values
      const currentTags = form.getValues("tags") || [];
      form.setValue("tags", [...currentTags, tag.id]);
    }
    
    setSelectedTagId("");
  };
  
  // Handle tag removal
  const handleRemoveTag = (tagId: number) => {
    setSelectedTags(selectedTags.filter(tag => tag.id !== tagId));
    
    // Update form values
    const currentTags = form.getValues("tags") || [];
    form.setValue("tags", currentTags.filter(id => id !== tagId));
  };
  
  // Handle form submission
  const onSubmit = (values: FormValues) => {
    createMutation.mutate(values);
  };
  
  // Preview content (would be processed markdown/html in a real app)
  const previewContent = form.watch("content");
  
  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>
                )}
              />
              
              <div>
                <FormLabel>Tags</FormLabel>
                <div className="flex flex-wrap gap-2 mb-2">
                  {selectedTags.map(tag => (
                    <Badge 
                      key={tag.id} 
                      variant="secondary"
                      className="px-2 py-1 flex items-center gap-1"
                    >
                      {tag.name}
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="h-4 w-4 p-0 text-navy/60 dark:text-cream/60 hover:text-navy hover:dark:text-cream hover:bg-transparent"
                        onClick={() => handleRemoveTag(tag.id)}
                      >
                        <X className="h-3 w-3" />
                        <span className="sr-only">Remove {tag.name}</span>
                      </Button>
                    </Badge>
                  ))}
                  
                  {selectedTags.length === 0 && (
                    <p className="text-sm text-navy/60 dark:text-cream/60">
                      No tags selected
                    </p>
                  )}
                </div>
                
                <div className="flex gap-2">
                  <Select 
                    value={selectedTagId} 
                    onValueChange={setSelectedTagId}
                  >
                    <SelectTrigger className="w-[200px]">
                      <SelectValue placeholder="Select a tag" />
                    </SelectTrigger>
                    <SelectContent>
                      {tags?.map(tag => (
                        <SelectItem 
                          key={tag.id} 
                          value={tag.id.toString()}
                          disabled={selectedTags.some(t => t.id === tag.id)}
                        >
                          {tag.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  
                  <Button
                    type="button"
                    variant="outline"
                    onClick={handleAddTag}
                    disabled={!selectedTagId}
                    className="flex items-center gap-1"
                  >
                    <Plus className="h-4 w-4" />
                    <span>Add Tag</span>
                  </Button>
                </div>
              </div>
              
              <FormField
                control={form.control}
                name="content"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Content</FormLabel>
                    <Tabs defaultValue="write">
                      <TabsList className="mb-2">
                        <TabsTrigger value="write">Write</TabsTrigger>
                        <TabsTrigger value="preview">Preview</TabsTrigger>
                      </TabsList>
                      
                      <TabsContent value="write" className="mt-0">
                        <EditorToolbar />
                        <FormControl>
                          <Textarea
                            placeholder="Write your article content here..."
                            className="resize-y min-h-96 font-serif leading-relaxed"
                            {...field}
                          />
                        </FormControl>
                      </TabsContent>
                      
                      <TabsContent value="preview" className="mt-0">
                        <div className="border border-sage/20 dark:border-sage/10 rounded-md p-4 min-h-96 prose prose-russet dark:prose-invert max-w-none">
                          {previewContent ? (
                            <div dangerouslySetInnerHTML={{ __html: previewContent.replace(/\n/g, '<br/>') }} />
                          ) : (
                            <p className="text-navy/60 dark:text-cream/60 italic">
                              Nothing to preview yet. Start writing in the "Write" tab.
                            </p>
                          )}
                        </div>
                      </TabsContent>
                    </Tabs>
                    <FormDescription>
                      You can use markdown formatting. The article will be attributed to your account.
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
              
              <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>
  );
}