import React, { useState, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { uploadBlogFile, generateBlogPostImage } from '@/shared/api/fileService';
import { generateBlogPost, newBlog, updateBlogPost, publishBlogPost } from '@/features/blog/api/blogService';
import { ArrowLeft, Sparkles, Upload, Image as ImageIcon, X, Loader2, Check } from 'lucide-react';
import { fetchBlogTopicSuggestions } from '@/features/blog/api/blogService';
import LanguageTabs from './LanguageTabs';
import SocialSchedulingPanel from './SocialSchedulingPanel';

const tonalities = ['Informativ', 'Inspirierend', 'Unterhaltsam', 'Formell'];
const languages = [
  { code: 'de', label: 'Deutsch' },
  { code: 'en', label: 'English' },
  { code: 'es', label: 'Español' },
];
const socialChannels = ['LinkedIn', 'Twitter', 'Facebook', 'Instagram'];

interface BlogWizardProps {
  onComplete: () => void;
  onNewBlog?: () => Promise<string>;
  onGenerate?: (args: { blog_Id: string; topic: string; tonality: string; languages: string[] }) => Promise<any>;
  onUpdate?: (args: { blogId: string; content: any }) => Promise<any>;
  onPublish?: (args: { blogId: string; publishDate?: string; publishToSocialMedia: boolean; socialMediaChannels: string[]; socialMediaLanguages: string[] }) => Promise<any>;
  onFetchSuggestions?: () => Promise<string[] | null>;
  onUploadFile?: (file: File, blogId: string) => Promise<{ success: boolean; url?: string; fileUrl?: string }>;
  onGenerateImage?: (blogId: string, title: string) => Promise<{ success: boolean; url?: string; fileUrl?: string }>;
}

type MediaItem = { id: string; url: string; type: 'image' | 'video' };

type WizardStep = 'topic' | 'loading' | 'result';

const BlogWizard: React.FC<BlogWizardProps> = ({ onComplete, onNewBlog, onGenerate, onUpdate, onPublish, onFetchSuggestions, onUploadFile, onGenerateImage }) => {
  const [step, setStep] = useState<WizardStep>('topic');
  const [topic, setTopic] = useState('');
  const [tone, setTone] = useState(tonalities[0]);
  const [selectedLangs, setSelectedLangs] = useState<string[]>(languages.map(lang => lang.code));
  const [isLoading, setIsLoading] = useState(false);
  const [generatedContent, setGeneratedContent] = useState<any>(null);
  const [editedContents, setEditedContents] = useState<Record<string, string>>({});
  const [initialContents, setInitialContents] = useState<Record<string, string>>({});
  const [activeLang, setActiveLang] = useState<string>('');
  const [uploadedMedia, setUploadedMedia] = useState<{id: string; url: string; type: 'image' | 'video'}[]>([]);
  const [selectedMediaId, setSelectedMediaId] = useState<string | null>(null);
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const [isGeneratingImage, setIsGeneratingImage] = useState(false);
  const [isLoadingSuggestions, setIsLoadingSuggestions] = useState(false);
  const [topicSuggestions, setTopicSuggestions] = useState<string[]>([]);
  const [isSaving, setIsSaving] = useState(false);
  const [blogId, setBlogId] = useState<string>('');
  const [showSocial, setShowSocial] = useState<boolean>(false);
  const [selectedChannels, setSelectedChannels] = useState<string[]>([]);
  const [scheduledTime, setScheduledTime] = useState<string>('');
  const fileInputRef = useRef<HTMLInputElement>(null);

  const hasChanges = React.useCallback((): boolean => {
    if (Object.keys(editedContents).length === 0) return false;
    return Object.keys(editedContents).some(
      lang => editedContents[lang] !== (initialContents[lang] || '')
    );
  }, [editedContents, initialContents]);

  const handleSaveChanges = React.useCallback(async () => {
    if (!hasChanges() || !blogId) return;
    
    setIsSaving(true);
    try {
      if (onUpdate) {
        await onUpdate({ blogId, content: editedContents });
      } else {
        await updateBlogPost({ blogId, content: editedContents });
      }
      setInitialContents({ ...editedContents });
    } catch (error) {
      console.error('Error saving changes:', error);
    } finally {
      setIsSaving(false);
    }
  }, [blogId, editedContents, hasChanges]);

  const handlePublish = async () => {
    try {
      if (!blogId) return;
      if (hasChanges()) {
        await handleSaveChanges();
      }
      if (onPublish) {
        await onPublish({
          blogId,
          publishDate: scheduledTime || undefined,
          publishToSocialMedia: showSocial && selectedChannels.length > 0,
          socialMediaChannels: showSocial ? selectedChannels : [],
          socialMediaLanguages: Object.keys(editedContents)
        });
      } else {
        await publishBlogPost({
          blogId,
          publishDate: scheduledTime || undefined,
          publishToSocialMedia: showSocial && selectedChannels.length > 0,
          socialMediaChannels: showSocial ? selectedChannels : [],
          socialMediaLanguages: Object.keys(editedContents)
        });
      }
      onComplete();
    } catch (error) {
      console.error('Error publishing blog post:', error);
    }
  };

  const handleRemoveImage = (id: string, e: React.MouseEvent) => {
    e.stopPropagation();
    setUploadedMedia(prev => prev.filter(media => media.id !== id));
    if (selectedMediaId === id) {
      setSelectedMediaId(uploadedMedia.length > 1 ? 
        uploadedMedia[0].id : null);
    }
  };

  const handleSelectImage = (id: string, e: React.MouseEvent) => {
    e.stopPropagation();
    setSelectedMediaId(id);
  };

  const handleImageClick = (e: React.MouseEvent, url: string) => {
    e.stopPropagation();
    setPreviewImage(url);
  };

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files?.[0]) return;
    
    const file = e.target.files[0];
    if (!file.type.startsWith('image/')) {
      return alert('Nur Bilder erlaubt');
    }

    try {
      let currentBlogId = blogId;
      if (!currentBlogId) {
        currentBlogId = onNewBlog ? await onNewBlog() : await newBlog();
        if (!currentBlogId) return;
        setBlogId(currentBlogId);
      }
      
      const res = onUploadFile ? await onUploadFile(file, currentBlogId) : await uploadBlogFile(file, currentBlogId);
      if (res.success && (res.url || res.fileUrl)) {
        const mediaItem = { 
          id: `file-${Date.now()}`,
          url: res.url || res.fileUrl || '',
          type: 'image' as const
        };
        setUploadedMedia(prev => [...prev, mediaItem]);
        setSelectedMediaId(mediaItem.id);
      }
    } catch (error) {
      console.error('Error uploading file:', error);
      alert('Fehler beim Hochladen der Datei');
    }
  };

  const handleGenerateImage = async () => {
    if (!topic.trim()) {
      alert('Bitte geben Sie zuerst ein Thema ein');
      return;
    }

    setIsGeneratingImage(true);
    try {
      let currentBlogId = blogId;
      if (!currentBlogId) {
        currentBlogId = onNewBlog ? await onNewBlog() : await newBlog();
        if (!currentBlogId) return;
        setBlogId(currentBlogId);
      }
      
      const result = onGenerateImage ? await onGenerateImage(currentBlogId, topic) : await generateBlogPostImage(currentBlogId, topic);
      if (result.success && (result.url || result.fileUrl)) {
        const mediaItem = { 
          id: `gen-${Date.now()}`,
          url: result.url || result.fileUrl || '',
          type: 'image' as const
        };
        setUploadedMedia(prev => [...prev, mediaItem]);
        setSelectedMediaId(mediaItem.id);
      }
    } catch (error) {
      console.error('Error generating image:', error);
      alert('Fehler beim Generieren des Bildes');
    } finally {
      setIsGeneratingImage(false);
    }
  };


  const handleGenerate = async () => {
    if (!topic.trim() || selectedLangs.length === 0) {
      alert('Bitte füllen Sie alle erforderlichen Felder aus');
      return;
    }
    
    if (!selectedMediaId) {
      alert('Bitte wählen Sie ein Bild aus');
      return;
    }
    
    setStep('loading');
    setIsLoading(true);
    
    try {
      const newBlogId = onNewBlog ? await onNewBlog() : await newBlog();
      if (!newBlogId) {
        throw new Error('Could not create a new blog entry');
      }

      setBlogId(newBlogId);
      const res = onGenerate
        ? await onGenerate({ blog_Id: newBlogId, topic, tonality: tone, languages: selectedLangs })
        : await generateBlogPost({ blog_Id: newBlogId, topic, tonality: tone, languages: selectedLangs });
      
      let blogArr = null;
      let gen = res;
      if (Array.isArray(res) && res[0]?.blog) {
        blogArr = res[0].blog;
        gen = res[0];
      } else if (res?.blog && Array.isArray(res.blog)) {
        blogArr = res.blog;
      }
      
      setGeneratedContent(gen);
      
      if (blogArr) {
        const contents: Record<string, string> = {};
        blogArr.forEach((entry: { language: string; content: string }) => {
          contents[entry.language] = entry.content;
        });
        setEditedContents(contents);
        setInitialContents(contents);
        setActiveLang(selectedLangs[0] || '');
      } else if (typeof gen === 'string') {
        setEditedContents({ de: gen });
        setInitialContents({ de: gen });
        setActiveLang('de');
      }
      
      setStep('result');
    } catch (error) {
      console.error('Error generating blog post:', error);
      setStep('topic');
      alert('Fehler beim Generieren des Blogbeitrags. Bitte versuchen Sie es erneut.');
    } finally {
      setIsLoading(false);
    }
  };

  

  const handleGetSuggestions = async () => {
    setIsLoadingSuggestions(true);
    try {
      const suggestions = onFetchSuggestions
        ? await onFetchSuggestions()
        : await fetchBlogTopicSuggestions();
      if (suggestions) {
        setTopicSuggestions(suggestions);
      }
    } catch (error) {
      console.error('Error fetching topic suggestions:', error);
    } finally {
      setIsLoadingSuggestions(false);
    }
  };
  const handleSelectSuggestion = (suggestion: string) => {
    setTopic(suggestion);
    setTopicSuggestions([]);
  };

  return (
    <>
      <Card className="w-full max-w-3xl mx-auto">
        <CardHeader>
          <CardTitle>
            {step === 'result' ? 'Neuen Blogbeitrag erstellen' : 'Blog Assistent'}
          </CardTitle>
        </CardHeader>
        <CardContent>
          {step === 'result' ? (
        <div className="space-y-6">
          <div className="flex justify-between items-center">
            <Button
              variant="outline"
              onClick={() => setStep('topic')}
              className="flex items-center gap-2"
            >
              <ArrowLeft className="h-4 w-4" />
              Zurück
            </Button>
          </div>

          <div className="space-y-4">
            <LanguageTabs 
              languages={languages}
              selectedLangs={selectedLangs}
              activeLang={activeLang}
              onSelect={setActiveLang}
            />

            {activeLang ? (
              <Textarea
                value={editedContents[activeLang] || ''}
                onChange={(e) =>
                  setEditedContents({ ...editedContents, [activeLang]: e.target.value })
                }
                rows={14}
                className="w-full text-sm"
              />
            ) : (
              <p className="text-muted-foreground">Kein Inhalt verfügbar</p>
            )}
            <div className="flex">
              <Button 
                variant="outline" 
                onClick={handleSaveChanges}
                disabled={!hasChanges() || isSaving}
              >
                {isSaving ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Wird gespeichert...
                  </>
                ) : 'Änderungen speichern'}
              </Button>
            </div>
          </div>

          {selectedMediaId && (
            <div className="mt-6">
              <h3 className="text-lg font-medium mb-2">Ausgewähltes Bild</h3>
              <div className="relative w-full max-w-md aspect-video rounded-lg overflow-hidden border">
                <img
                  src={uploadedMedia.find(m => m.id === selectedMediaId)?.url}
                  alt="Ausgewähltes Blog-Bild"
                  className="w-full h-full object-cover"
                />
              </div>
            </div>
          )}
        </div>
      ) : step === 'loading' ? (
        <div className="flex flex-col items-center justify-center py-12">
          <Loader2 className="h-8 w-8 animate-spin text-primary mb-4" />
          <p className="text-muted-foreground">Beitrag wird generiert...</p>
        </div>
      ) : (
            <div className="space-y-6">
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <Label htmlFor="topic">Thema des Blogbeitrags</Label>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="text-sm text-muted-foreground"
                    onClick={handleGetSuggestions}
                    disabled={isLoadingSuggestions}
                  >
                    {isLoadingSuggestions ? (
                      <>
                        <span className="h-4 w-4 border-2 border-muted-foreground/50 border-t-primary rounded-full animate-spin mr-2" />
                        Lade Vorschläge...
                      </>
                    ) : (
                      <>
                        <Sparkles className="h-4 w-4 mr-1.5" />
                        Thema vorschlagen lassen
                      </>
                    )}
                  </Button>
                </div>
                <div className="relative">
                  <Input
                    id="topic"
                    placeholder="Zum Beispiel: Die besten Tipps für erfolgreiches Social Media Marketing"
                    value={topic}
                    onChange={(e) => setTopic(e.target.value)}
                  />
                  {topicSuggestions.length > 0 && (
                    <div className="absolute z-10 w-full mt-1 bg-white dark:bg-gray-800 border rounded-md shadow-lg">
                      <div className="p-2 text-sm text-muted-foreground">Themenvorschläge:</div>
                      {topicSuggestions.map((suggestion, index) => (
                        <button
                          key={index}
                          type="button"
                          className="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700"
                          onClick={() => handleSelectSuggestion(suggestion)}
                        >
                          {suggestion}
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </div>

              <div className="flex flex-col space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>Ton</Label>
                    <Select value={tone} onValueChange={setTone}>
                      <SelectTrigger>
                        <SelectValue placeholder="Ton auswählen" />
                      </SelectTrigger>
                      <SelectContent>
                        {tonalities.map((tone) => (
                          <SelectItem key={tone} value={tone}>
                            {tone}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label>Sprachen</Label>
                    <div className="flex items-center space-x-4">
                      {languages.map((lang) => (
                        <div key={lang.code} className="flex items-center space-x-1.5">
                          <input
                            type="checkbox"
                            id={`lang-${lang.code}`}
                            checked={selectedLangs.includes(lang.code)}
                            onChange={(e) => {
                              if (e.target.checked) {
                                setSelectedLangs([...selectedLangs, lang.code]);
                              } else {
                                setSelectedLangs(selectedLangs.filter(l => l !== lang.code));
                              }
                            }}
                            className="h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary"
                          />
                          <Label htmlFor={`lang-${lang.code}`} className="text-sm font-medium leading-none">
                            {lang.label}
                          </Label>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              </div>

              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-2">
                    <Label>Medien</Label>
                  
                  </div>
                
                  <div className="flex items-center space-x-2">
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      className="h-8 text-xs"
                      onClick={() => fileInputRef.current?.click()}
                    >
                      <Upload className="h-3.5 w-3.5 mr-1.5" />
                      Hochladen
                    </Button>
                    <input
                      ref={fileInputRef}
                      type="file"
                      className="hidden"
                      accept="image/*"
                      onChange={handleImageUpload}
                    />
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      className="h-8 text-xs"
                      onClick={handleGenerateImage}
                      disabled={!topic.trim() || isGeneratingImage}
                    >
                      {isGeneratingImage ? (
                        <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
                      ) : (
                        <Sparkles className="h-3.5 w-3.5 mr-1.5" />
                      )}
                      KI-Bild generieren
                    </Button>
                  </div>
                </div>

                {uploadedMedia.length > 0 && (
                  <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
                    {uploadedMedia.map((media) => {
                      const isSelected = selectedMediaId === media.id;
                      return (
                        <div 
                          key={media.id}
                          onClick={(e) => handleImageClick(e, media.url)}
                          className={`relative group rounded-md overflow-hidden border-2 cursor-pointer transition-all ${
                            isSelected ? 'border-primary ring-2 ring-primary' : 'border-transparent hover:border-muted-foreground/30'
                          }`}
                        >
                          <div className="aspect-square bg-muted/50 flex items-center justify-center">
                            <ImageIcon className="h-8 w-8 text-muted-foreground" />
                          </div>
                          <img
                            src={media.url}
                            alt=""
                            className="absolute inset-0 w-full h-full object-cover"
                          />
                          <div 
                            onClick={(e) => handleSelectImage(media.id, e)}
                            className={`absolute top-1 right-1 w-5 h-5 rounded flex items-center justify-center transition-colors ${
                              isSelected 
                                ? 'bg-primary text-primary-foreground' 
                                : 'bg-background/90 text-foreground/50 hover:bg-background/80 hover:text-foreground/70'
                            }`}
                          >
                            {isSelected && <Check className="h-3.5 w-3.5" />}
                          </div>
                          <button
                            type="button"
                            onClick={(e) => handleRemoveImage(media.id, e)}
                            className="absolute top-1 left-1 p-1 rounded-full bg-destructive text-destructive-foreground opacity-0 group-hover:opacity-100 transition-opacity"
                          >
                            <X className="h-3 w-3" />
                          </button>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>

              <div className="flex justify-end">
                <Button 
                  onClick={handleGenerate} 
                  disabled={!topic.trim() || isLoading || !selectedMediaId}
                >
                  {isLoading ? 'Wird generiert...' : 'Beitrag generieren'}
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
      {step === 'result' && (
        <SocialSchedulingPanel 
          showSocial={showSocial}
          onToggleSocial={() => setShowSocial((v) => !v)}
          socialChannels={socialChannels}
          selectedChannels={selectedChannels}
          onToggleChannel={(c) => setSelectedChannels((prev) => prev.includes(c) ? prev.filter(ch => ch !== c) : [...prev, c])}
          languages={languages}
          selectedLangs={selectedLangs}
          editedContents={editedContents}
          initialContents={initialContents}
          activeLang={activeLang}
          setActiveLang={setActiveLang}
          setEditedContents={setEditedContents}
          scheduledTime={scheduledTime}
          setScheduledTime={setScheduledTime}
          onPublish={handlePublish}
          canPublish={!hasChanges()}
        />
      )}
      {previewImage && (
        <div 
          className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4"
          onClick={() => setPreviewImage(null)}
        >
          <div className="relative max-w-4xl w-full max-h-[90vh]">
            <button 
              className="absolute -top-10 right-0 text-white hover:text-gray-300"
              onClick={(e) => {
                e.stopPropagation();
                setPreviewImage(null);
              }}
            >
              <X className="w-6 h-6" />
            </button>
            <div className="bg-background rounded-lg overflow-hidden">
              <img 
                src={previewImage} 
                alt="Vorschau" 
                className="w-full h-auto max-h-[80vh] object-contain mx-auto"
                onClick={(e) => e.stopPropagation()}
              />
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default BlogWizard;
