import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/hooks/useAuth';
import { useUserRole } from '@/hooks/useUserRole';
import { AdminLayout } from '@/components/layout/AdminLayout';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { UppyPhotoUploadLazy } from '@/components/upload/UppyPhotoUploadLazy';
import { MarkdownEditorLazy } from '@/components/admin/MarkdownEditorLazy';
import { generateSlugFromName } from '@/lib/slugUtils';
import { extractCloudflareImageId } from '@/lib/cloudflareImageUtils';
import { Edit, Trash2, Eye, Plus } from 'lucide-react';
import { toast } from 'sonner';
import { formatDistanceToNow } from 'date-fns';
import { useDocumentTitle } from '@/hooks/useDocumentTitle';

interface BlogPost {
  id: string;
  slug: string;
  title: string;
  content: string;
  featured_image_id?: string;
  featured_image_url?: string;
  status: 'draft' | 'published';
  published_at?: string;
  view_count: number;
  created_at: string;
}

export default function AdminBlog() {
  useDocumentTitle('Blog Management - Admin');
  const { user } = useAuth();
  const { isAdmin, loading } = useUserRole();
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  const [activeTab, setActiveTab] = useState('posts');
  const [editingPost, setEditingPost] = useState<BlogPost | null>(null);
  
  const [title, setTitle] = useState('');
  const [slug, setSlug] = useState('');
  const [content, setContent] = useState('');
  const [featuredImageId, setFeaturedImageId] = useState('');
  const [featuredImageUrl, setFeaturedImageUrl] = useState('');

  // All mutations must be called before conditional returns
  const saveMutation = useMutation({
    mutationFn: async ({ isDraft }: { isDraft: boolean }) => {
      const postData = {
        title,
        slug,
        content,
        featured_image_id: featuredImageId || null,
        featured_image_url: featuredImageUrl || null,
        author_id: user!.id,
        status: isDraft ? 'draft' : 'published',
        published_at: isDraft ? null : new Date().toISOString(),
      };

      if (editingPost) {
        const { error } = await supabase
          .from('blog_posts')
          .update(postData)
          .eq('id', editingPost.id);
        if (error) throw error;
      } else {
        const { error } = await supabase
          .from('blog_posts')
          .insert(postData);
        if (error) throw error;
      }
    },
    onSuccess: (_, { isDraft }) => {
      queryClient.invalidateQueries({ queryKey: ['admin-blog-posts'] });
      toast.success(isDraft ? 'Draft saved' : 'Post published');
      resetForm();
      setActiveTab('posts');
    },
    onError: (error) => {
      toast.error('Failed to save post: ' + error.message);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase
        .from('blog_posts')
        .delete()
        .eq('id', id);
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-blog-posts'] });
      toast.success('Post deleted');
    },
    onError: (error) => {
      toast.error('Failed to delete post: ' + error.message);
    },
  });

  const { data: posts, isLoading } = useQuery({
    queryKey: ['admin-blog-posts'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('blog_posts')
        .select('*')
        .order('created_at', { ascending: false });
      if (error) throw error;
      return data as BlogPost[];
    },
  });

  // useEffect must be called before conditional returns
  useEffect(() => {
    if (!loading && !isAdmin()) {
      navigate('/');
    }
  }, [loading, isAdmin, navigate]);

  // Show loading state while checking permissions
  if (loading) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center min-h-[60vh]">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
            <p className="text-muted-foreground">Loading...</p>
          </div>
        </div>
      </AdminLayout>
    );
  }

  // Don't render if not admin
  if (!loading && !isAdmin()) {
    return null;
  }

  const resetForm = () => {
    setTitle('');
    setSlug('');
    setContent('');
    setFeaturedImageId('');
    setFeaturedImageUrl('');
    setEditingPost(null);
  };

  const loadPostForEditing = (post: BlogPost) => {
    setEditingPost(post);
    setTitle(post.title);
    setSlug(post.slug);
    setContent(post.content);
    setFeaturedImageId(post.featured_image_id || '');
    setFeaturedImageUrl(post.featured_image_url || '');
    setActiveTab('editor');
  };

  const handleTitleChange = (newTitle: string) => {
    setTitle(newTitle);
    if (!editingPost) {
      setSlug(generateSlugFromName(newTitle));
    }
  };

  const handleImageUpload = (imageId: string, imageUrl: string) => {
    setFeaturedImageId(imageId);
    setFeaturedImageUrl(imageUrl);
  };

  return (
    <AdminLayout>
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-bold">Blog Management</h1>
          <p className="text-muted-foreground">Create and manage blog posts</p>
        </div>

        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList>
            <TabsTrigger value="posts">Posts</TabsTrigger>
            <TabsTrigger value="editor">
              {editingPost ? 'Edit Post' : 'New Post'}
            </TabsTrigger>
          </TabsList>

          <TabsContent value="posts" className="space-y-4">
            <div className="flex justify-between items-center">
              <p className="text-sm text-muted-foreground">
                {posts?.length || 0} total posts
              </p>
              <Button onClick={() => {
                resetForm();
                setActiveTab('editor');
              }}>
                <Plus className="w-4 h-4 mr-2" />
                New Post
              </Button>
            </div>

            <Card>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Title</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Published</TableHead>
                    <TableHead>Views</TableHead>
                    <TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {isLoading ? (
                    <TableRow>
                      <TableCell colSpan={5} className="text-center">
                        Loading...
                      </TableCell>
                    </TableRow>
                  ) : posts?.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={5} className="text-center">
                        No posts yet. Create your first post!
                      </TableCell>
                    </TableRow>
                  ) : (
                    posts?.map((post) => (
                      <TableRow key={post.id}>
                        <TableCell className="font-medium">
                          {post.title}
                        </TableCell>
                        <TableCell>
                          <Badge variant={post.status === 'published' ? 'default' : 'secondary'}>
                            {post.status}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          {post.published_at 
                            ? formatDistanceToNow(new Date(post.published_at), { addSuffix: true })
                            : '-'
                          }
                        </TableCell>
                        <TableCell>{post.view_count}</TableCell>
                        <TableCell className="text-right space-x-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => window.open(`/blog/${post.slug}`, '_blank')}
                          >
                            <Eye className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => loadPostForEditing(post)}
                          >
                            <Edit className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              if (confirm('Delete this post?')) {
                                deleteMutation.mutate(post.id);
                              }
                            }}
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </Card>
          </TabsContent>

          <TabsContent value="editor" className="space-y-6">
            <Card className="p-6 space-y-6">
              <div className="space-y-2">
                <Label htmlFor="title">Title *</Label>
                <Input
                  id="title"
                  value={title}
                  onChange={(e) => handleTitleChange(e.target.value)}
                  placeholder="Enter post title..."
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="slug">Slug *</Label>
                <Input
                  id="slug"
                  value={slug}
                  onChange={(e) => setSlug(e.target.value)}
                  placeholder="post-url-slug"
                />
                <p className="text-xs text-muted-foreground">
                  URL: /blog/{slug || 'post-url-slug'}
                </p>
              </div>

              <div className="space-y-2">
                <Label>Featured Image</Label>
                <UppyPhotoUploadLazy
                  onUploadComplete={(urls) => {
                    if (urls.length > 0) {
                      const url = urls[0];
                      const imageId = extractCloudflareImageId(url);
                      if (imageId) {
                        handleImageUpload(imageId, url);
                        toast.success('Image uploaded');
                      }
                    }
                  }}
                  maxFiles={1}
                />
                {featuredImageUrl && (
                  <img 
                    src={featuredImageUrl} 
                    alt="Preview" 
                    className="w-full max-w-md rounded-lg"
                  />
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="content">Content (Markdown) *</Label>
                <MarkdownEditorLazy
                  value={content}
                  onChange={setContent}
                  onSave={async (value) => {
                    if (editingPost) {
                      await supabase
                        .from('blog_posts')
                        .update({ content: value, updated_at: new Date().toISOString() })
                        .eq('id', editingPost.id);
                    }
                  }}
                  autoSave={!!editingPost}
                  height={600}
                  placeholder="Write your blog post in markdown..."
                />
              </div>

              <div className="flex gap-3">
                <Button
                  onClick={() => saveMutation.mutate({ isDraft: true })}
                  disabled={!title || !slug || !content || saveMutation.isPending}
                  variant="outline"
                >
                  Save Draft
                </Button>
                <Button
                  onClick={() => saveMutation.mutate({ isDraft: false })}
                  disabled={!title || !slug || !content || saveMutation.isPending}
                >
                  Publish
                </Button>
                <Button
                  variant="ghost"
                  onClick={() => {
                    resetForm();
                    setActiveTab('posts');
                  }}
                >
                  Cancel
                </Button>
              </div>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </AdminLayout>
  );
}
