"use client"

import React, { useState, useRef, useEffect } from "react"
import { X, Star, Sparkles, FileText, ImageIcon, Video, ArrowRight, Download, Plus, Save } from "lucide-react"
import { router, usePage } from "@inertiajs/react"
import TemplateBrowser from "./TemplateBrowser"
import { route } from "ziggy-js"
import axios from "axios"
import { Modal } from "@/Components/UI/Modal"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/UI/Select"

export default function AiAssistance({ isOpen, onClose, onApply, t, ai_modules, platforms = [], templates =[] }) {
  const { props } = usePage()
  const user = props.auth?.user
  const [inputValue, setInputValue] = useState("")
  const [templateBrowserOpen, setTemplateBrowserOpen] = useState(false)
  const [selectedModule, setSelectedModule] = useState("text")
  const [isGenerating, setIsGenerating] = useState(false)
  const [generatedContent, setGeneratedContent] = useState(null)
  const [error, setError] = useState(null)
  const [chatHistory, setChatHistory] = useState([])
  const [showGreeting, setShowGreeting] = useState(true)
  const panelRef = useRef(null)
  const chatContainerRef = useRef(null)
  const [saveTemplateModalOpen, setSaveTemplateModalOpen] = useState(false)
  const [templatePrompt, setTemplatePrompt] = useState("")
  const [intendedPlatform, setIntendedPlatform] = useState(platforms.find(p => p.slug === "facebook")?.id || null)
  const [templateName, setTemplateName] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)


  const modules = {
    text: {
      name: ai_modules?.text?.name || 'Text',
      ...ai_modules?.text,
      icon: FileText
    },
    image: {
      name: ai_modules?.image?.name || 'Images',
      ...ai_modules?.image,
      icon: ImageIcon
    },
    video: {
      name: ai_modules?.video?.name || 'Videos',
      ...ai_modules?.video,
      icon: Video
    },
  }  

  const suggestions = templates.slice(0, 4).map(t => t.prompt);

  const handleKeyPress = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault()
      handleSend()
    }
    // Allow Shift+Enter for new lines (default textarea behavior)
  }

  const handleTemplateBrowser = () => {
    setTemplateBrowserOpen(true)
  }

  const handleSuggestionClick = (suggestion) => {
    setInputValue(suggestion)
  }

  const handleSend = async () => {
    if (!inputValue.trim()) return

    // Hide greeting when user starts chatting
    setShowGreeting(false)

    const userPrompt = {
      id: Date.now(),
      type: "user",
      content: inputValue,
      module: selectedModule,
      timestamp: new Date(),
    }

    setChatHistory((prev) => [...prev, userPrompt])
    const currentPrompt = inputValue
    setInputValue("")
    setIsGenerating(true)
    setError(null)
    setGeneratedContent(null)

    try {
      // Prepare conversation history for context
      const conversationHistory = chatHistory.filter(msg =>
        msg.type === 'user' || msg.type === 'ai'
      ).slice(-6).map(msg => ({
        role: msg.type === 'user' ? 'user' : 'assistant',
        content: msg.type === 'user'
          ? msg.content
          : (msg.content?.content || msg.content?.message || '')
      })).filter(msg => msg.content && msg.content.trim() !== '')

      const { data } = await axios.post(route("user.ai.generate"), {
        prompt: currentPrompt,
        module: selectedModule,
        conversation_history: conversationHistory,
      })

      // Handle success case
      if (data.status === 'success') {
        const aiResponse = {
          id: Date.now() + 1,
          type: "ai",
          content: data,
          module: selectedModule,
          timestamp: new Date(),
        }

        setChatHistory((prev) => [...prev, aiResponse])
        setGeneratedContent(data)
        return
      }

      // Handle error case from backend
      if (data.status === 'error') {
        const errorMessage = data.message || "AI generation failed"
        setError(errorMessage)

        // Add error message to chat history
        const errorResponse = {
          id: Date.now() + 1,
          type: "error",
          content: { message: errorMessage },
          module: selectedModule,
          timestamp: new Date(),
        }
        setChatHistory((prev) => [...prev, errorResponse])
        return
      }

      // Fallback for unexpected response format
      setError("Unexpected response format from server")

    } catch (err) {
      console.error('AI Generation Error:', err)
      let errorMessage = "Failed to generate content"

      if (err.response) {
        // Handle HTTP error responses
        const statusCode = err.response.status
        const responseData = err.response.data

        switch (statusCode) {
          case 422:
            errorMessage = responseData.message || "Invalid request parameters"
            break
          case 500:
            errorMessage = "AI service is temporarily unavailable. Please check your AI configuration."
            break
          case 404:
            errorMessage = "AI generation service not found"
            break
          default:
            errorMessage = responseData.message || `Server error (${statusCode})`
        }
      } else if (err.request) {
        errorMessage = "Unable to reach AI service. Please check your connection."
      }

      setError(errorMessage)

      // Add error to chat history
      const errorResponse = {
        id: Date.now() + 1,
        type: "error",
        content: { message: errorMessage },
        module: selectedModule,
        timestamp: new Date(),
      }
      setChatHistory((prev) => [...prev, errorResponse])

    } finally {
      setIsGenerating(false)
    }
  }

  const handleSavePromptAsTemplate = (prompt) => {
    setSaveTemplateModalOpen(true)
    setTemplatePrompt(prompt)

  }

  const handleSaveTemplate = (e) => {
    e.preventDefault()
    setIsSubmitting(true)
    router.post(route("user.template.ai.store"), {
      name: templateName ?? "Ai Template",
      prompt: templatePrompt,
      platform_id: intendedPlatform
    },
      {
        onSuccess: () => {
          setIsSubmitting(false)
          setSaveTemplateModalOpen(false)
        },
        onError: () => {
          setIsSubmitting(false)
          setSaveTemplateModalOpen(false)
        }
      })

  }

  const handleReusePrompt = (prompt) => {
    setInputValue(prompt)
  }

  const handleDownload = (item) => {
    try {
      if (item.module === "text") {
        const blob = new Blob([item.content.content], { type: "text/plain" })
        triggerDownload(blob, item.title || "ai-generated-content.txt")
        return
      }

      if (item.module === "image" || item.module === "video") {
        fetch(item.content.url || item.thumbnail)
          .then((res) => res.blob())
          .then((blob) => {
            const ext = item.module === "image" ? "png" : "mp4"
            triggerDownload(blob, (item.title || `ai-generated-${item.module}`) + `.${ext}`)
          })
          .catch(() => alert("Download failed"))
      }
    } catch (err) {
      console.error("Download error:", err)
      alert("Download failed")
    }
  }

  const triggerDownload = (blob, filename) => {
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement("a")
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  }


  const renderShimmer = () => {
    if (selectedModule === "text") {
      return (
        <div className="space-y-3">
          <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
          <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded animate-pulse w-3/4"></div>
          <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded animate-pulse w-1/2"></div>
        </div>
      )
    } else if (selectedModule === "image") {
      return (
        <div className="grid grid-cols-2 gap-3">
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="aspect-square bg-gray-200 dark:bg-gray-700 rounded-lg animate-pulse"></div>
          ))}
        </div>
      )
    } else if (selectedModule === "video") {
      return (
        <div className="aspect-video bg-gray-200 dark:bg-gray-700 rounded-lg animate-pulse flex items-center justify-center">
          <Video className="w-12 h-12 text-gray-400 animate-pulse" />
        </div>
      )
    }
  }

  const renderChatHistory = () => {
    return (
      <div className="space-y-4 mb-6">
        {chatHistory.map((item) => (
          <div key={item.id}>
            {item.type === "user" ? (
              // User prompt bubble
              <div className="flex justify-end">
                <div className="max-w-[80%] bg-gradient-to-r from-primary to-secondary text-white rounded-2xl rounded-br-md px-4 py-3 relative group shadow-sm">
                  <p className="text-sm leading-relaxed">{item.content}</p>
                  <div className="flex items-center justify-between mt-2 pt-2 border-t border-white/20">
                    <span className="text-xs text-white/80 capitalize flex items-center gap-1">
                      {modules[item.module]?.icon && (
                        <span className="inline-block w-3 h-3">
                          {React.createElement(modules[item.module].icon, { className: "w-3 h-3" })}
                        </span>
                      )}
                      {item.module}
                    </span>
                    <div className="flex items-center space-x-1 opacity-0 group-hover:opacity-100 transition-opacity">
                      <button
                        onClick={() => handleReusePrompt(item.content)}
                        className="p-1 text-white/80 hover:text-white hover:bg-white/20 rounded transition-all"
                        title="Reuse prompt"
                      >
                        <ArrowRight className="w-3 h-3" />
                      </button>
                      <button
                        onClick={() => handleSavePromptAsTemplate(item.content)}
                        className="p-1 text-white/80 hover:text-white hover:bg-white/20 rounded transition-all"
                        title="Save as template"
                      >
                        <Save className="w-3 h-3" />
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            ) : item.type === "error" ? (
              // Error message bubble
              <div className="flex justify-start">
                <div className="max-w-[80%] bg-red-50 dark:bg-red-900/20 rounded-2xl rounded-bl-md px-4 py-3 border border-red-200 dark:border-red-800 shadow-sm">
                  <div className="flex items-center mb-2">
                    <div className="w-5 h-5 bg-red-500 rounded-full flex items-center justify-center mr-2 shadow-sm">
                      <X className="w-3 h-3 text-white" />
                    </div>
                    <span className="text-xs font-medium text-red-600 dark:text-red-400">
                      Configuration Error
                    </span>
                  </div>
                  <p className="text-sm text-red-700 dark:text-red-300 leading-relaxed">
                    {item.content.message}
                  </p>
                  <div className="mt-2 pt-2 border-t border-red-200 dark:border-red-800">
                    <p className="text-xs text-red-600 dark:text-red-400">
                      💡 Please configure your AI settings in the admin panel to use this feature.
                    </p>
                  </div>
                </div>
              </div>
            ) : (
              // AI response bubble
              <div className="flex justify-start">
                <div className="max-w-[80%] bg-gray-50 dark:bg-zinc-800 rounded-2xl rounded-bl-md px-4 py-3 border border-gray-200 dark:border-gray-600 shadow-sm">
                  <div className="flex items-center mb-2">
                    <div className="w-5 h-5 bg-gradient-to-r from-primary to-secondary rounded-full flex items-center justify-center mr-2 shadow-sm">
                      <Sparkles className="w-3 h-3 text-white" />
                    </div>
                    <span className="text-xs font-medium text-gray-600 dark:text-gray-400 capitalize">
                      AI {item.module} Response
                    </span>
                  </div>

                  {item.module === "text" && (
                    <p className="text-sm text-gray-700 dark:text-gray-300 leading-relaxed whitespace-pre-wrap">
                      {item.content.content}
                    </p>
                  )}

                  {item.module === "image" && item.content.urls && (
                    <div className="grid grid-cols-2 gap-2">
                      {item.content.urls.map((url, index) => (
                        <img
                          key={index}
                          src={url || "/placeholder.svg"}
                          alt={`Generated image ${index + 1}`}
                          className="w-full aspect-square object-cover rounded-lg"
                        />
                      ))}
                    </div>
                  )}

                  {item.module === "video" && item.content.url && (
                    <video
                      src={item.content.url}
                      controls
                      className="w-full aspect-video rounded-lg"
                      poster="/video-placeholder.png"
                    />
                  )}

                  <div className="flex items-center justify-end mt-3 pt-2 border-t border-gray-200 dark:border-gray-600 space-x-1">
                    <button
                      onClick={() => {
                        if (onApply) {
                          onApply(item.content)
                          onClose()
                        }
                      }}
                      className="p-1 text-gray-500 hover:text-cyan-600 hover:bg-gray-200 dark:hover:bg-gray-600 rounded transition-colors"
                      title="Insert into composer"
                    >
                      <Plus className="w-3 h-3" />
                    </button>
                    <button
                      onClick={() => handleDownload(item)}
                      className="p-1 text-gray-500 hover:text-cyan-600 hover:bg-gray-200 dark:hover:bg-gray-600 rounded transition-colors"
                      title="Download"
                    >
                      <Download className="w-3 h-3" />
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>
    )
  }

  const handleModuleSwitch = (moduleKey) => {
    setSelectedModule(moduleKey)
  }

  const handleAITemplateSelect = (template) => {
    setInputValue(template.description)
    setTemplateBrowserOpen(false)
  }

  // Auto-scroll to bottom when chat history changes
  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight
    }
  }, [chatHistory, isGenerating])

  // Reset greeting when modal opens
  useEffect(() => {
    if (isOpen && chatHistory.length === 0) {
      setShowGreeting(true)
    }
  }, [isOpen, chatHistory.length])

  if (!isOpen) return null

  return (
    <>
      <div className="fixed inset-0 z-50 flex">
        <div className="flex-1 backdrop-blur-sm bg-black/20" onClick={onClose} />

        <div
          ref={panelRef}
          className={`w-96 bg-white dark:bg-zinc-900 shadow-2xl transform transition-transform duration-300 ease-out ${isOpen ? "translate-x-0" : "translate-x-full"
            }`}
        >
          <div className="h-full flex flex-col">
            <div className="p-6 text-center border-b border-gray-200 dark:border-zinc-800">
              <button
                onClick={onClose}
                className="absolute top-4 right-4 p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              >
                <X className="w-5 h-5" />
              </button>

              <div className="w-16 h-16 bg-gradient-to-r from-primary to-secondary rounded-full flex items-center justify-center mx-auto mb-4 shadow-lg">
                <Sparkles className="w-8 h-8 text-white animate-bounce" />
              </div>

              <h2 className="text-2xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 dark:from-white dark:to-gray-200 bg-clip-text text-transparent mb-2">
                AI Content Assistant
              </h2>
              <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                Generate professional content with AI
              </p>

              {/* Simple Status Bar */}
              <div className="bg-gradient-to-r from-primary/10 to-secondary/10 dark:from-primary/20 dark:to-secondary/20 rounded-lg p-3 border border-primary/20 mb-4">
                <div className="flex items-center justify-center gap-2">
                  {modules[selectedModule]?.icon && React.createElement(modules[selectedModule].icon, {
                    className: "w-5 h-5 text-primary"
                  })}
                  <span className="text-sm font-semibold text-gray-800 dark:text-gray-200">
                    {isGenerating
                      ? `Generating ${modules[selectedModule]?.name || selectedModule}...`
                      : `You are generating ${modules[selectedModule]?.name || selectedModule}`
                    }
                  </span>
                </div>
              </div>
            </div>

            <div ref={chatContainerRef} className="flex-1 p-6 overflow-y-auto scroll-smooth">
              {chatHistory.length > 0 && renderChatHistory()}

              {chatHistory.length === 0 && showGreeting && (
                <div className="flex flex-col items-center justify-center text-center py-8 px-4">
                  {/* Animated Greeting */}
                  <div className="mb-6"> 
                    <div className="space-y-2">
                      <h3 className="text-xl font-bold text-gray-900 dark:text-white animate-fade-in">
                        Good to see you here, {user?.name || 'there'}! 👋
                      </h3>
                      <p className="text-sm text-gray-600 dark:text-gray-400 animate-fade-in-delay max-w-xs mx-auto leading-relaxed">
                        I'm your AI assistant, ready to help you create amazing content. What would you like to generate today?
                      </p>
                    </div>
                  </div>

                  {/* Helpful Tips */}
                  <div className="grid grid-cols-1 gap-3 w-full max-w-sm">
                    <div className="flex items-center gap-3 p-3 bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20 rounded-lg border border-blue-200 dark:border-blue-800 animate-slide-up">
                      <FileText className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0" />
                      <span className="text-sm text-blue-700 dark:text-blue-300">Generate text content</span>
                    </div>

                    <div className="flex items-center gap-3 p-3 bg-gradient-to-r from-emerald-50 to-green-50 dark:from-emerald-900/20 dark:to-green-900/20 rounded-lg border border-emerald-200 dark:border-emerald-800 animate-slide-up-delay">
                      <ImageIcon className="w-5 h-5 text-emerald-600 dark:text-emerald-400 flex-shrink-0" />
                      <span className="text-sm text-emerald-700 dark:text-emerald-300">Create images</span>
                    </div>

                    <div className="flex items-center gap-3 p-3 bg-gradient-to-r from-purple-50 to-pink-50 dark:from-purple-900/20 dark:to-pink-900/20 rounded-lg border border-purple-200 dark:border-purple-800 animate-slide-up-delay-2">
                      <Video className="w-5 h-5 text-purple-600 dark:text-purple-400 flex-shrink-0" />
                      <span className="text-sm text-purple-700 dark:text-purple-300">Generate videos</span>
                    </div>
                  </div>
                </div>
              )}

              {isGenerating && (
                <div className="flex justify-start mb-4">
                  <div className="max-w-[80%] bg-gray-100 dark:bg-gray-700 rounded-2xl rounded-bl-md px-4 py-3">
                    <div className="flex items-center mb-2">
                      <div className="w-2 h-2 bg-gradient-to-r from-primary to-secondary rounded-full animate-pulse mr-2"></div>
                      <p className="text-sm text-gray-600 dark:text-gray-400">
                        Generating {modules[selectedModule]?.name || selectedModule}...
                      </p>
                    </div>
                    {renderShimmer()}
                  </div>
                </div>
              )}
            </div>

            <div className="p-6 border-t border-gray-200 dark:border-zinc-800">
              <div className="relative">
                <textarea
                  value={inputValue}
                  onChange={(e) => setInputValue(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder={t("Write something...")}
                  rows={3}
                  className="w-full px-4 py-3 pr-16 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-zinc-800 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-cyan-500 focus:border-transparent resize-none"
                />

                <button
                  onClick={handleSend}
                  disabled={!inputValue.trim() || isGenerating}
                  className="absolute bottom-3 right-3 px-3 py-1.5 bg-gradient-to-r from-primary to-secondary hover:from-secondary hover:to-primary disabled:from-gray-300 disabled:to-gray-400 disabled:cursor-not-allowed text-white rounded-lg flex items-center justify-center transition-all shadow-sm hover:shadow-md"
                >
                  {isGenerating ? (
                    <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  ) : (
                    <ArrowRight className="w-4 h-4" />
                  )}
                </button>
              </div>

              {/* Content Type Selection - Below Text Box */}
              <div className="flex items-center justify-between mt-4">
                <div className="flex items-center space-x-2">
                  <button
                    onClick={handleTemplateBrowser}
                    className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                    title="Browse templates"
                  >
                    <Sparkles className="w-4 h-4" />
                  </button>
                </div>

                {/* Content Type Icons */}
                <div className="flex items-center space-x-2">
                  {Object.entries(modules).map(([key, module]) => {
                    const IconComponent = module.icon
                    const isSelected = selectedModule === key
                    return (
                      <button
                        key={key}
                        onClick={() => handleModuleSwitch(key)}
                        className={`p-2 rounded-lg transition-all ${
                          isSelected
                            ? "bg-gradient-to-r from-primary to-secondary text-white shadow-sm"
                            : "text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                        }`}
                        title={module.name || key}
                      >
                        <IconComponent className="w-5 h-5" />
                      </button>
                    )
                  })}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Save Template Modal */}
      <Modal
        isOpen={saveTemplateModalOpen}
        onClose={() => {
          setSaveTemplateModalOpen(false)
          setTemplateName("")
          setTemplatePrompt("")
          setSaveAsTemplate(false)
        }}
        title={t("Save Ai Template")}
        onSubmit={handleSaveTemplate}
        submitText={t("Save Template")}
        showSubmit={true}
        isDataSubmitting={isSubmitting}

      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {t("Template Name")}
            </label>
            <input
              type="text"
              value={templateName}
              onChange={(e) => setTemplateName(e.target.value)}
              placeholder={t("Enter template name")}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-zinc-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-cyan-500 focus:border-transparent"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {t("Prompt")}
            </label>
            <textarea
              value={templatePrompt}
              onChange={(e) => setTemplatePrompt(e.target.value)}
              placeholder={t("Describe what this template is for")}
              rows={3}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-zinc-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-cyan-500 focus:border-transparent resize-none"
            />
          </div>

          {/* Platform select */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Select Platform
            </label>
            <Select
              value={intendedPlatform}
              onValueChange={(value) => setIntendedPlatform(value)}
            >
              <SelectTrigger className="w-full min-w-[180px] bg-gray-50 border-gray-200 dark:bg-zinc-800 dark:border-none dark:text-neutral-200">
                <SelectValue placeholder="Choose a platform" />
              </SelectTrigger>
              <SelectContent>
                {platforms.map((platform) => (
                  <SelectItem key={platform.id} value={platform.id}>
                    {platform.name}
                  </SelectItem>
                ))}

              </SelectContent>
            </Select>
          </div>
        </div>
      </Modal>

      <TemplateBrowser
        isOpen={templateBrowserOpen}
        onClose={() => setTemplateBrowserOpen(false)}
        onApply={handleAITemplateSelect}
        t={t}
        templates = {templates}
        platforms={platforms}
      />
    </>
  )
}
