import React, { useState } from 'react';
import { AuthenticatedLayout } from '../layout/AuthenticatedLayout';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Textarea } from '../ui/textarea';
import { Badge } from '../ui/badge';
import { toast } from "sonner";
import { ArrowLeft, Upload, X, Plus } from 'lucide-react';
import { Route } from '../../types/routes';
import { useCreateBlogMutation } from '../../store/services/contentManager.service';

interface NewBlogProps {
  onNavigate: (route: Route) => void;
  onLogout: () => void;
  user: any;
  formData?: any;
  onAutoSave?: (data: any) => void;
  onClearAutoSave?: (route?: string) => void;
}

export function NewBlog({ 
  onNavigate, 
  onLogout, 
  user, 
  formData,
  onAutoSave,
  onClearAutoSave 
}: NewBlogProps) {
  const [blogData, setBlogData] = useState(() => ({
    title: formData?.title || '',
    urlSlug: formData?.urlSlug || '',
    content: formData?.content || '',
    bannerImage: formData?.bannerImage || '',
    category: formData?.category || '',
    tags: formData?.tags || [],
    metaTitle: formData?.metaTitle || '',
    metaDesc: formData?.metaDesc || '',
    publishedAt: formData?.publishedAt || new Date().toISOString()
  }));

  const [newTag, setNewTag] = useState('');
  const [isUploading, setIsUploading] = useState(false);
  
  // Use the RTK Query mutation hook
  const [createBlog, { isLoading: isSubmitting }] = useCreateBlogMutation();

  // Auto-save functionality
  React.useEffect(() => {
    if (onAutoSave) {
      const timer = setTimeout(() => {
        onAutoSave(blogData);
      }, 1000);
      return () => clearTimeout(timer);
    }
  }, [blogData, onAutoSave]);

  const handleInputChange = (field: string, value: any) => {
    setBlogData(prev => ({
      ...prev,
      [field]: value
    }));

    // Auto-generate URL slug from title
    if (field === 'title' && !blogData.urlSlug) {
      const slug = value.toLowerCase()
        .replace(/[^a-z0-9\s-]/g, '')
        .replace(/\s+/g, '-')
        .replace(/-+/g, '-')
        .trim();
      setBlogData(prev => ({
        ...prev,
        urlSlug: slug
      }));
    }
  };

  const handleImageUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    if (!file.type.startsWith('image/')) {
      toast.error('Please select a valid image file');
      return;
    }

    setIsUploading(true);
    try {
      // Simulate upload - replace with actual image upload API
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // For now, we'll use a placeholder. In production, you'd upload to your server/CDN
      const imageUrl = URL.createObjectURL(file);
      handleInputChange('bannerImage', imageUrl);
      
      toast.success('Banner image uploaded successfully');
    } catch (error) {
      toast.error('Failed to upload image');
    } finally {
      setIsUploading(false);
    }
  };

  const addTag = () => {
    if (newTag.trim() && !blogData.tags.includes(newTag.trim())) {
      handleInputChange('tags', [...blogData.tags, newTag.trim()]);
      setNewTag('');
    }
  };

  const removeTag = (tagToRemove: string) => {
    handleInputChange('tags', blogData.tags.filter((tag: string) => tag !== tagToRemove));
  };

  const handleCreateBlog = async (status: 'draft' | 'published') => {
    if (!blogData.title.trim()) {
      toast.error('Please enter a blog title');
      return;
    }

    if (!blogData.content.trim()) {
      toast.error('Please enter blog content');
      return;
    }

    if (!blogData.category) {
      toast.error('Please select a category');
      return;
    }

    try {
      const blogPayload = {
        title: blogData.title,
        urlSlug: blogData.urlSlug,
        content: blogData.content,
        bannerImage: blogData.bannerImage,
        category: blogData.category,
        tags: blogData.tags,
        metaTitle: blogData.metaTitle,
        metaDesc: blogData.metaDesc,
        publishedAt: status === 'published' ? new Date().toISOString() : null
      };

      // Use the RTK Query mutation
      await createBlog(blogPayload).unwrap();

      if (onClearAutoSave) {
        onClearAutoSave();
      }
      
      toast.success(`Blog ${status === 'draft' ? 'saved as draft' : 'published'} successfully`);
      onNavigate('/content');
    } catch (error: any) {
      console.error('Error creating blog:', error);
      
      // Handle different error formats
      if (error.data?.message) {
        if (Array.isArray(error.data.message)) {
          error.data.message.forEach((msg: string) => toast.error(msg));
        } else {
          toast.error(error.data.message);
        }
      } else {
        toast.error(error.message || 'Failed to save blog. Please try again.');
      }
    }
  };

  const categories = ['Technology', 'Business', 'Marketing', 'Design', 'Development', 'Personal Development', 'Leadership', 'Other'];

  return (
    <AuthenticatedLayout
      user={user}
      onLogout={onLogout}
      currentPath="/content/blogs/new"
    >
      <div className="space-y-6 mt-[20px] mr-[20px] mb-[0px] ml-[20px]">
        <div className="flex items-center gap-4">
          <Button
            variant="ghost"
            onClick={() => onNavigate('/content')}
            className="min-h-[44px] focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary)] focus-visible:ring-opacity-50"
            disabled={isSubmitting}
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back to Content
          </Button>
          <div>
            <h1>Create New Blog Post</h1>
            <p className="text-muted-foreground mt-1">
              Write and publish a new blog post for your audience
            </p>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Main Content */}
          <div className="lg:col-span-2 space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>Blog Content</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="title">Title *</Label>
                  <Input
                    id="title"
                    value={blogData.title}
                    onChange={(e) => handleInputChange('title', e.target.value)}
                    placeholder="Enter blog title"
                    className="min-h-[44px] focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary)] focus-visible:ring-opacity-50"
                    disabled={isSubmitting}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="urlSlug">URL Slug</Label>
                  <Input
                    id="urlSlug"
                    value={blogData.urlSlug}
                    onChange={(e) => handleInputChange('urlSlug', e.target.value)}
                    placeholder="blog-url-slug"
                    className="min-h-[44px] focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary)] focus-visible:ring-opacity-50"
                    disabled={isSubmitting}
                  />
                  <p className="text-sm text-muted-foreground">
                    URL: /blog/{blogData.urlSlug || 'blog-url-slug'}
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="content">Content *</Label>
                  <Textarea
                    id="content"
                    value={blogData.content}
                    onChange={(e) => handleInputChange('content', e.target.value)}
                    placeholder="Write your blog content here..."
                    rows={15}
                    className="min-h-[300px] resize-y focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary)] focus-visible:ring-opacity-50"
                    disabled={isSubmitting}
                  />
                </div>
              </CardContent>
            </Card>

            {/* SEO Settings */}
            <Card>
              <CardHeader>
                <CardTitle>SEO Settings</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="metaTitle">Meta Title</Label>
                  <Input
                    id="metaTitle"
                    value={blogData.metaTitle}
                    onChange={(e) => handleInputChange('metaTitle', e.target.value)}
                    placeholder="SEO optimized title"
                    maxLength={60}
                    className="min-h-[44px] focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary)] focus-visible:ring-opacity-50"
                    disabled={isSubmitting}
                  />
                  <p className="text-sm text-muted-foreground">
                    {blogData.metaTitle.length}/60 characters
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="metaDesc">Meta Description</Label>
                  <Textarea
                    id="metaDesc"
                    value={blogData.metaDesc}
                    onChange={(e) => handleInputChange('metaDesc', e.target.value)}
                    placeholder="Brief description for search engines"
                    maxLength={160}
                    rows={3}
                    className="resize-y focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary)] focus-visible:ring-opacity-50"
                    disabled={isSubmitting}
                  />
                  <p className="text-sm text-muted-foreground">
                    {blogData.metaDesc.length}/160 characters
                  </p>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Sidebar */}
          <div className="space-y-6">
            {/* Banner Image */}
            <Card>
              <CardHeader>
                <CardTitle>Banner Image</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                {blogData.bannerImage ? (
                  <div className="space-y-2">
                    <div className="relative">
                      <img
                        src={blogData.bannerImage}
                        alt="Banner preview"
                        className="w-full h-32 object-cover rounded border"
                      />
                      <Button
                        variant="destructive"
                        size="sm"
                        onClick={() => handleInputChange('bannerImage', '')}
                        className="absolute top-2 right-2 min-h-[32px] h-8 w-8 p-0"
                        disabled={isSubmitting}
                      >
                        <X className="h-4 w-4" />
                      </Button>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      Image URL: {blogData.bannerImage}
                    </p>
                  </div>
                ) : (
                  <div className="space-y-2">
                    <input
                      type="file"
                      accept="image/*"
                      onChange={handleImageUpload}
                      className="hidden"
                      id="banner-upload"
                      disabled={isSubmitting}
                    />
                    <Label
                      htmlFor="banner-upload"
                      className={`flex flex-col items-center justify-center w-full h-32 border-2 border-dashed border-muted-foreground/25 rounded cursor-pointer hover:border-muted-foreground/50 transition-colors ${
                        isSubmitting ? 'opacity-50 cursor-not-allowed' : ''
                      }`}
                    >
                      {isUploading ? (
                        <div className="text-center">
                          <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary mx-auto"></div>
                          <p className="text-sm text-muted-foreground mt-2">Uploading...</p>
                        </div>
                      ) : (
                        <div className="text-center">
                          <Upload className="h-6 w-6 text-muted-foreground mx-auto" />
                          <p className="text-sm text-muted-foreground mt-2">Click to upload banner</p>
                          <p className="text-xs text-muted-foreground mt-1">Or enter URL in field below</p>
                        </div>
                      )}
                    </Label>
                  </div>
                )}
                
                <div className="space-y-2">
                  <Label htmlFor="bannerImageUrl">Banner Image URL</Label>
                  <Input
                    id="bannerImageUrl"
                    value={blogData.bannerImage}
                    onChange={(e) => handleInputChange('bannerImage', e.target.value)}
                    placeholder="https://example.com/image.jpg"
                    className="min-h-[44px] focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary)] focus-visible:ring-opacity-50"
                    disabled={isSubmitting}
                  />
                </div>
              </CardContent>
            </Card>

            {/* Category & Tags */}
            <Card>
              <CardHeader>
                <CardTitle>Classification</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="category">Category *</Label>
                  <select
                    id="category"
                    value={blogData.category}
                    onChange={(e) => handleInputChange('category', e.target.value)}
                    className="w-full min-h-[44px] px-3 py-2 border border-input bg-background rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary)] focus-visible:ring-opacity-50"
                    disabled={isSubmitting}
                  >
                    <option value="">Select category</option>
                    {categories.map(category => (
                      <option key={category} value={category}>{category}</option>
                    ))}
                  </select>
                </div>

                <div className="space-y-2">
                  <Label>Tags</Label>
                  <div className="flex gap-2">
                    <Input
                      value={newTag}
                      onChange={(e) => setNewTag(e.target.value)}
                      placeholder="Add tag"
                      onKeyPress={(e) => {
                        if (e.key === 'Enter') {
                          e.preventDefault();
                          addTag();
                        }
                      }}
                      className="min-h-[44px] focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary)] focus-visible:ring-opacity-50"
                      disabled={isSubmitting}
                    />
                    <Button
                      type="button"
                      onClick={addTag}
                      variant="outline"
                      className="min-h-[44px] focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary)] focus-visible:ring-opacity-50"
                      disabled={isSubmitting}
                    >
                      <Plus className="h-4 w-4" />
                    </Button>
                  </div>
                  {blogData.tags.length > 0 && (
                    <div className="flex flex-wrap gap-2 mt-2">
                      {blogData.tags.map((tag: string) => (
                        <Badge
                          key={tag}
                          variant="secondary"
                          className="flex items-center gap-1"
                        >
                          {tag}
                          <X
                            className="h-3 w-3 cursor-pointer"
                            onClick={() => !isSubmitting && removeTag(tag)}
                          />
                        </Badge>
                      ))}
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>

            {/* Actions */}
            <Card>
              <CardHeader>
                <CardTitle>Publish</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <Button
                  onClick={() => handleCreateBlog('draft')}
                  variant="outline"
                  disabled={isSubmitting}
                  className="w-full min-h-[44px] focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary)] focus-visible:ring-opacity-50"
                >
                  {isSubmitting ? 'Saving...' : 'Save as Draft'}
                </Button>
                <Button
                  onClick={() => handleCreateBlog('published')}
                  disabled={isSubmitting}
                  className="w-full min-h-[44px] focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary)] focus-visible:ring-opacity-50"
                  style={{ backgroundColor: "var(--color-brand-primary)" }}
                >
                  {isSubmitting ? 'Publishing...' : 'Publish Blog'}
                </Button>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </AuthenticatedLayout>
  );
}