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@2.0.3";
import { ArrowLeft, Upload, X, Plus } from 'lucide-react';

interface NewBlogProps {
  onNavigate: (route: string) => 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 || '',
    slug: formData?.slug || '',
    metaTitle: formData?.metaTitle || '',
    metaDescription: formData?.metaDescription || '',
    body: formData?.body || '',
    bannerImage: formData?.bannerImage || null,
    bannerAltText: formData?.bannerAltText || '',
    tags: formData?.tags || [],
    category: formData?.category || '',
    status: formData?.status || 'draft'
  }));

  const [newTag, setNewTag] = useState('');
  const [isUploading, setIsUploading] = useState(false);

  // 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 slug from title
    if (field === 'title' && !blogData.slug) {
      const slug = value.toLowerCase()
        .replace(/[^a-z0-9\s-]/g, '')
        .replace(/\s+/g, '-')
        .replace(/-+/g, '-')
        .trim();
      setBlogData(prev => ({
        ...prev,
        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
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      const imageUrl = URL.createObjectURL(file);
      handleInputChange('bannerImage', {
        url: imageUrl,
        name: file.name,
        size: file.size
      });
      
      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 handleSave = async (status: 'draft' | 'published') => {
    if (!blogData.title.trim()) {
      toast.error('Please enter a blog title');
      return;
    }

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

    try {
      const blogToSave = {
        ...blogData,
        status,
        id: Date.now().toString(),
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        author: user.name
      };

      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      if (onClearAutoSave) {
        onClearAutoSave();
      }
      
      toast.success(`Blog ${status === 'draft' ? 'saved as draft' : 'published'} successfully`);
      onNavigate('/content');
    } catch (error) {
      toast.error('Failed to save blog');
    }
  };

  const categories = ['Technology', 'Business', 'Marketing', 'Design', 'Development', '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"
          >
            <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"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="slug">URL Slug</Label>
                  <Input
                    id="slug"
                    value={blogData.slug}
                    onChange={(e) => handleInputChange('slug', 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"
                  />
                  <p className="text-sm text-muted-foreground">
                    URL: /blog/{blogData.slug || 'blog-url-slug'}
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="body">Content *</Label>
                  <Textarea
                    id="body"
                    value={blogData.body}
                    onChange={(e) => handleInputChange('body', 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"
                  />
                </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"
                  />
                  <p className="text-sm text-muted-foreground">
                    {blogData.metaTitle.length}/60 characters
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="metaDescription">Meta Description</Label>
                  <Textarea
                    id="metaDescription"
                    value={blogData.metaDescription}
                    onChange={(e) => handleInputChange('metaDescription', 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"
                  />
                  <p className="text-sm text-muted-foreground">
                    {blogData.metaDescription.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.url}
                        alt="Banner preview"
                        className="w-full h-32 object-cover rounded border"
                      />
                      <Button
                        variant="destructive"
                        size="sm"
                        onClick={() => handleInputChange('bannerImage', null)}
                        className="absolute top-2 right-2 min-h-[32px] h-8 w-8 p-0"
                      >
                        <X className="h-4 w-4" />
                      </Button>
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="bannerAltText">Alt Text</Label>
                      <Input
                        id="bannerAltText"
                        value={blogData.bannerAltText}
                        onChange={(e) => handleInputChange('bannerAltText', e.target.value)}
                        placeholder="Describe the image"
                        className="min-h-[44px] focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary)] focus-visible:ring-opacity-50"
                      />
                    </div>
                  </div>
                ) : (
                  <div className="space-y-2">
                    <input
                      type="file"
                      accept="image/*"
                      onChange={handleImageUpload}
                      className="hidden"
                      id="banner-upload"
                    />
                    <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"
                    >
                      {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>
                        </div>
                      )}
                    </Label>
                  </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"
                  >
                    <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"
                    />
                    <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"
                    >
                      <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={() => removeTag(tag)}
                          />
                        </Badge>
                      ))}
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>

            {/* Actions */}
            <Card>
              <CardHeader>
                <CardTitle>Publish</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <Button
                  onClick={() => handleSave('draft')}
                  variant="outline"
                  className="w-full min-h-[44px] focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary)] focus-visible:ring-opacity-50"
                >
                  Save as Draft
                </Button>
                <Button
                  onClick={() => handleSave('published')}
                  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)" }}
                >
                  Publish Blog
                </Button>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </AuthenticatedLayout>
  );
}