import React, { useState, useEffect, useRef } from "react";
import MDEditor, { commands } from '@uiw/react-md-editor';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from './ui/select';
import { Button } from './ui/button';
import { Separator } from './ui/separator';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from './ui/dialog';
import { CustomTabs } from './ui/tabs';

const PUBLIC_MINIO_UPLOAD_URL = import.meta.env.PUBLIC_MINIO_UPLOAD_URL;
const PUBLIC_TOPIC_API_URL = import.meta.env.PUBLIC_TOPIC_API_URL;

const NewTopic = () => {

  // Form state
  const [formData, setFormData] = useState({ status: 'draft', category: '', title: '', content: '', imageUrl: '' });
  // UI state
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(false);
  const [imageFile, setImageFile] = useState(null);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [imageDialogOpen, setImageDialogOpen] = useState(false);
  const [imageUrlInput, setImageUrlInput] = useState('');
  const [imageUploadFile, setImageUploadFile] = useState(null);
  const [imageUploadPreview, setImageUploadPreview] = useState('');
  const [editorMode, setEditorMode] = useState('edit');

  // Upload file to MinIO
  const uploadToMinIO = async (file, onProgress) => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('api_key', 'wweifwehfwfhwhtuyegbvijvbfvegfreyf');

    try {
      const response = await fetch(PUBLIC_MINIO_UPLOAD_URL, {
        method: 'POST',
        body: formData,
        credentials: 'include',
      });

      if (!response.ok) {
        throw new Error('Upload failed');
      }

      const data = await response.json();
      console.log(data)
      return data.url;
    } catch (error) {
      console.error('Upload error:', error);
      throw error;
    }
  };

  // // Generate slug from title
  // useEffect(() => {
  //   if (formData.title) {
  //     const slug = formData.title
  //       .toLowerCase()
  //       .replace(/[^\w\s]/g, '')
  //       .replace(/\s+/g, '-');
  //     setFormData(prev => ({ ...prev, slug }));
  //   }
  // }, [formData.title]);

  const customImageCommand = {
    name: 'image',
    keyCommand: 'image',
    buttonProps: { 'aria-label': 'Insert image' },
    icon: (
      <svg width="12" height="12" viewBox="0 0 20 20">
        <path fill="currentColor" d="M15 9c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm4-7H1c-.55 0-1 .45-1 1v14c0 .55.45 1 1 1h18c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm-1 13l-6-5-2 2-4-5-4 8V4h16v11z"/>
      </svg>
    ),
    execute: () => {
      setImageDialogOpen(true);
    },
  };
  
  // Get all default commands and replace the image command
  const allCommands = commands.getCommands().map(cmd => {
    if (cmd.name === 'image') {
      return customImageCommand;
    }
    return cmd;
  });
  

  // Handle image URL insertion
  const handleInsertImageUrl = () => {
    if (imageUrlInput) {
      const imgMarkdown = `![Image](${imageUrlInput})`;
      const textarea = document.querySelector('.w-md-editor-text-input');
      if (textarea) {
        const startPos = textarea.selectionStart;
        const endPos = textarea.selectionEnd;
        const currentValue = formData.content;
        
        const newValue = 
          currentValue.substring(0, startPos) + 
          imgMarkdown + 
          currentValue.substring(endPos);
        
        setFormData(prev => ({ ...prev, content: newValue }));
      }
      setImageDialogOpen(false);
      setImageUrlInput('');
    }
  };

  // Handle image file selection
  const handleImageFileSelect = (e) => {
    const file = e.target.files[0];
    if (file) {
      setImageUploadFile(file);
      
      // Create preview
      const reader = new FileReader();
      reader.onload = () => {
        setImageUploadPreview(reader.result);
      };
      reader.readAsDataURL(file);
    }
  };

  // Upload image file to MinIO and insert into editor
  const handleImageUpload = async () => {
    if (!imageUploadFile) return;
    
    try {
      setIsSubmitting(true);
      setUploadProgress(0);
      
      const uploadedUrl = await uploadToMinIO(imageUploadFile, (progress) => {
        setUploadProgress(progress);
      });
      
      // Insert markdown for the uploaded image
      const imgMarkdown = `![Image](${uploadedUrl})`;
      const textarea = document.querySelector('.w-md-editor-text-input');
      if (textarea) {
        const startPos = textarea.selectionStart;
        const endPos = textarea.selectionEnd;
        const currentValue = formData.content;
        
        const newValue = 
          currentValue.substring(0, startPos) + 
          imgMarkdown + 
          currentValue.substring(endPos);
        
        setFormData(prev => ({ ...prev, content: newValue }));
      }
      
      setImageDialogOpen(false);
      setImageUploadFile(null);
      setImageUploadPreview('');
    } catch (error) {
      setError('Failed to upload image: ' + error.message);
    } finally {
      setIsSubmitting(false);
    }
  };

  // Form submission
  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    setError(null);
    setUploadProgress(0);

    try {
      // Upload featured image if selected
      let imageUrl = formData.imageUrl;
      if (imageFile) {
        imageUrl = await uploadToMinIO(imageFile, (progress) => {
          setUploadProgress(progress);
        });
      }

      // Prepare payload
      const payload = {
        ...formData,
        imageUrl
      };

      // Submit to API
      const response = await fetch(`${PUBLIC_TOPIC_API_URL}?query=create-new-topic`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify(payload)
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || 'Failed to create topic');
      }

      setSuccess(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setIsSubmitting(false);
      setUploadProgress(0);
    }
  };

  // Handle form field changes
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  // Handle featured image file selection
  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      setImageFile(file);
      // Preview image
      const reader = new FileReader();
      reader.onload = () => {
        setFormData(prev => ({ ...prev, imageUrl: reader.result }));
      };
      reader.readAsDataURL(file);
    }
  };

  // Reset form
  const resetForm = () => {
    setFormData({
      status: 'draft',
      category: '',
      title: '',
      slug: '',
      content: '',
      imageUrl: ''
    });
    setImageFile(null);
    setSuccess(false);
    setError(null);
  };

  // Success state
  if (success) {
    return (
      <div className="container mx-auto px-4 text-center py-8">
        <h3 className="text-xl font-semibold text-green-600 mb-4">Topic created successfully!</h3>
        <div className="flex justify-center gap-4">
          <Button onClick={resetForm}>Create Another</Button>
          <Button variant="outline" onClick={() => window.location.href = '/'}>Return Home</Button>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-3xl mx-auto bg-neutral-800 rounded-lg shadow-md p-6">
        <h2 className="text-2xl font-bold text-[#6d9e37] mb-2">Create New Topic</h2>
        <p className="text-gray-600 mb-6">Start a new discussion in the SiliconPin community</p>

        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="space-y-2">
              <Label htmlFor="status">Status</Label>
              <Select 
                name="status" 
                required 
                value={formData.status} 
                onValueChange={(value) => setFormData(prev => ({ ...prev, status: value }))}
              >
                <SelectTrigger id="status" className="text-sm sm:text-base w-full">
                  <SelectValue placeholder="Select status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="draft">Draft</SelectItem>
                  <SelectItem value="published">Published</SelectItem>
                  <SelectItem value="archived">Archived</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label htmlFor="category">Category *</Label>
              <Select 
                name="category" 
                required 
                value={formData.category} 
                onValueChange={(value) => setFormData(prev => ({ ...prev, category: value }))}
              >
                <SelectTrigger id="category" className="text-sm sm:text-base w-full">
                  <SelectValue placeholder="Select a category" />
                </SelectTrigger>
                <SelectContent position="popper" className="z-50">
                  <SelectItem value="php">PHP Hosting</SelectItem>
                  <SelectItem value="nodejs">Node.js Hosting</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* Title and Slug */}
          <div className="space-y-2">
            <Label htmlFor="title">Title *</Label>
            <Input type="text" name="title" value={formData.title} onChange={handleChange} placeholder="Enter a descriptive title" required />
          </div>

          {/* <div className="space-y-2">
            <Label htmlFor="slug">URL Slug</Label>
            <Input type="text" name="slug" value={formData.slug} onChange={handleChange} readOnly className="bg-gray-50" />
            <p className="text-xs text-gray-500">This will be used in the topic URL</p>
          </div> */}

          {/* Content Editor with Preview Toggle */}
          <div className="space-y-2">
            <div className="flex justify-between items-center">
              <Label htmlFor="content">Content *</Label>
              <button 
                type="button" 
                size="sm"
                onClick={() => setEditorMode(editorMode === 'edit' ? 'preview' : 'edit')}
                className={`ml-2  ${editorMode !== 'edit' ? 'bg-[#6d9e37]' : ''} text-white border border-[#6d9e37] text-[#6d9e37] px-2 py-1 rounded-md`}
              >
                {editorMode === 'edit' ? 'Preview' : 'Edit'}
              </button>
            </div>
            <div data-color-mode="light">
            <MDEditor
              placeholder="Write your content" 
              value={formData.content} 
              onChange={(value) => setFormData(prev => ({ ...prev, content: value || '' }))} 
              height={400} 
              preview={editorMode}
              commands={allCommands}
            />
            </div>
          </div>

          {/* Image Upload Dialog */}
          <Dialog open={imageDialogOpen} onOpenChange={setImageDialogOpen}>
            <DialogContent className="sm:max-w-[425px]">
              <DialogHeader>
                <DialogTitle>Insert Image</DialogTitle>
              </DialogHeader>
              <CustomTabs
                tabs={[
                  {
                    label: "From URL",
                    value: "url",
                    content: (
                      <div className="space-y-4">
                        <Input
                          type="text"
                          placeholder="Enter image URL"
                          value={imageUrlInput}
                          onChange={(e) => setImageUrlInput(e.target.value)}
                        />
                        <div className="flex justify-end">
                          <Button 
                            type="button" 
                            onClick={handleInsertImageUrl}
                            disabled={!imageUrlInput}
                          >
                            Insert Image
                          </Button>
                        </div>
                      </div>
                    )
                  },
                  {
                    label: "Upload",
                    value: "upload",
                    content: (
                      <div className="space-y-4">
                        <Input
                          type="file"
                          accept="image/*"
                          onChange={handleImageFileSelect}
                        />
                        {imageUploadPreview && (
                          <div className="mt-2">
                            <img 
                              src={imageUploadPreview} 
                              alt="Preview" 
                              className="max-h-40 rounded-md border"
                            />
                          </div>
                        )}
                        {uploadProgress > 0 && uploadProgress < 100 && (
                          <div className="w-full bg-gray-200 rounded-full h-2.5">
                            <div 
                              className="bg-blue-600 h-2.5 rounded-full" 
                              style={{ width: `${uploadProgress}%` }}
                            ></div>
                          </div>
                        )}
                        <div className="flex justify-end">
                          <Button 
                            type="button" 
                            onClick={handleImageUpload}
                            disabled={!imageUploadFile || isSubmitting}
                          >
                            {isSubmitting ? 'Uploading...' : 'Upload & Insert'}
                          </Button>
                        </div>
                      </div>
                    )
                  }
                ]}
              />
            </DialogContent>
          </Dialog>

          {/* Featured Image Upload */}
          <div className="space-y-2">
            <Label htmlFor="image">Featured Image</Label>
            <Input 
              type="file" 
              id="image" 
              onChange={handleFileChange} 
              accept="image/*" 
              className="cursor-pointer" 
            />
            
            {uploadProgress > 0 && uploadProgress < 100 && (
              <div className="w-full bg-gray-200 rounded-full h-2.5">
                <div 
                  className="bg-blue-600 h-2.5 rounded-full" 
                  style={{ width: `${uploadProgress}%` }}
                ></div>
              </div>
            )}

            {formData.imageUrl && (
              <div className="mt-2">
                <img 
                  src={formData.imageUrl} 
                  alt="Preview" 
                  className="max-h-40 rounded-md border"
                />
              </div>
            )}
          </div>

          <Separator />

          {/* Form Actions */}
          <div className="flex justify-end gap-4">
            <Button 
              type="button" 
              variant="outline" 
              onClick={resetForm} 
              disabled={isSubmitting}
            >
              Reset
            </Button>
            <Button 
              type="submit" 
              disabled={isSubmitting} 
              className="min-w-32"
            >
              {isSubmitting ? (
                <span className="flex items-center gap-2">
                  <span className="animate-spin">↻</span>
                  Creating...
                </span>
              ) : 'Create Topic'}
            </Button>
          </div>

          {error && (
            <div className="p-4 bg-red-50 text-red-600 rounded-md">
              Error: {error}
            </div>
          )}
        </form>
      </div>
    </div>
  );
};

export default NewTopic;