"use client"

import { useState, useRef, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { FileText, LinkIcon, Upload, Zap, CheckCircle2, File } from "lucide-react"
import { getApiUrl } from "@/lib/env"
import { trackEvent } from "@/utils/analytics"

interface MockToolInterfaceProps {
  buttonText?: string;
  ctaLink?: string;
}

export function MockToolInterface({ buttonText = "Process with AI", ctaLink = "https://app.codeframeai.com" }: MockToolInterfaceProps) {
  const [activeTab, setActiveTab] = useState("upload")
  const [isProcessing, setIsProcessing] = useState(false)
  const [progress, setProgress] = useState(0)
  const [isDone, setIsDone] = useState(false)
  const [fileName, setFileName] = useState<string | null>(null)
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [url, setUrl] = useState("")
  const [mounted, setMounted] = useState(false)
  const [validationError, setValidationError] = useState<string | null>(null)

  const fileInputRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    setMounted(true)
  }, [])

  const handleProcess = async () => {
    setValidationError(null)
    if (activeTab === "upload") {
      if (!selectedFile) {
        setValidationError("Please select a file first!")
        return
      }
      const maxSizeBytes = 5 * 1024 * 1024 // 5MB
      if (selectedFile.size > maxSizeBytes) {
        setValidationError("Maximum file size limit is 5MB.")
        return
      }
    }
    if (activeTab === "url" && !url) {
      setValidationError("Please paste a URL first!")
      return
    }

    // Track the analyze click event
    trackEvent('analyze_click', { type: activeTab === 'upload' ? 'file' : 'url' });

    setIsProcessing(true)
    setIsDone(false)
    setProgress(0)

    let redirectUrl = ""

    try {
      const isLocalhost = typeof window !== 'undefined' && (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1')
      const studentAppUrl = isLocalhost ? "http://localhost:3001" : "https://app.codeframeai.com"

      if (activeTab === "upload" && selectedFile) {
        setProgress(15)
        const formData = new FormData()
        formData.append("file", selectedFile)
        formData.append("fileName", selectedFile.name)

        const uploadUrl = getApiUrl("/upload_video_file")
        const response = await fetch(uploadUrl, {
          method: "POST",
          body: formData,
        })

        if (!response.ok) {
          throw new Error("Upload failed")
        }

        const data = await response.json()
        const fileURL = data.fileURL

        redirectUrl = `${studentAppUrl}/#/login?source=external&type=file&fileName=${encodeURIComponent(selectedFile.name)}&fileURL=${encodeURIComponent(fileURL)}`
        setProgress(60)
      } else if (activeTab === "url" && url) {
        const isYoutube = url.includes("youtube.com") || url.includes("youtu.be");
        if (isYoutube) {
          setProgress(10);
          try {
            const checkRes = await fetch('/api/video-duration', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ videoUrl: url }),
            });
            const checkData = await checkRes.json();
            if (!checkRes.ok || !checkData.success) {
              setValidationError(checkData.error || "Failed to validate video duration.");
              setIsProcessing(false);
              return;
            }
            if (checkData.durationSeconds > 1800) { // 30 minutes
              setValidationError(`Maximum video duration allowed is 30 minutes. This video is ${checkData.durationText}.`);
              setIsProcessing(false);
              return;
            }
          } catch (err: any) {
            console.error("Error validating video length:", err);
            setValidationError("Error validating video length. Please try again.");
            setIsProcessing(false);
            return;
          }
        }
        setProgress(30)
        redirectUrl = `${studentAppUrl}/#/login?source=external&type=video_link&url=${encodeURIComponent(url)}`
      }

      const interval = setInterval(() => {
        setProgress((prev) => {
          if (prev >= 100) {
            clearInterval(interval)
            setIsProcessing(false)
            setIsDone(true)

            // Redirect to the actual app after a short delay
            setTimeout(() => {
              window.location.href = redirectUrl
            }, 1000)

            return 100
          }
          return prev + 10
        })
      }, 80)
    } catch (error) {
      console.error("Error uploading file:", error)
      setValidationError("An error occurred during file processing. Please try again.")
      setIsProcessing(false)
    }
  }

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    setValidationError(null)
    if (file) {
      const maxSizeBytes = 5 * 1024 * 1024 // 5MB
      if (file.size > maxSizeBytes) {
        setValidationError("Maximum file size limit is 5MB.")
        setFileName(null)
        setSelectedFile(null)
        e.target.value = ""
        return
      }
      setFileName(file.name)
      setSelectedFile(file)
    }
  }

  const triggerFileInput = () => {
    fileInputRef.current?.click()
  }

  // Prevent hydration mismatch by not rendering the interactive part on the server
  if (!mounted) {
    return (
      <div className="bg-card/90 backdrop-blur-md border border-primary/20 rounded-2xl shadow-[0_20px_50px_-20px_rgba(13,148,136,0.3)] p-6 max-w-2xl mx-auto mt-2 h-[300px] flex items-center justify-center">
        <div className="text-muted-foreground">Loading tool...</div>
      </div>
    )
  }

  return (
    <div className="bg-card/90 backdrop-blur-md border border-primary/20 rounded-2xl shadow-[0_20px_50px_-20px_rgba(13,148,136,0.3)] p-6 max-w-2xl mx-auto mt-2 transition-all duration-500 hover:shadow-[0_20px_50px_-10px_rgba(13,148,136,0.4)] relative text-left">
      {/* Glow Effect */}
      <div className="absolute -top-10 -left-10 w-40 h-40 bg-primary/10 rounded-full blur-3xl -z-10" />
      <div className="absolute -bottom-10 -right-10 w-40 h-40 bg-accent/10 rounded-full blur-3xl -z-10" />

      <div className="flex gap-4 mb-6 border-b border-border/50 pb-2">
        <button
          className={`px-4 py-2 text-sm font-bold transition-colors relative ${activeTab === "upload" ? "text-primary" : "text-zinc-400 hover:text-white"}`}
          onClick={() => {
            setActiveTab("upload");
            setValidationError(null);
          }}
        >
          Upload File
          {activeTab === "upload" && (
            <div className="absolute bottom-[-9px] left-0 right-0 h-0.5 bg-gradient-to-r from-primary to-accent" />
          )}
        </button>
        <button
          className={`px-4 py-2 text-sm font-bold transition-colors relative ${activeTab === "url" ? "text-primary" : "text-zinc-400 hover:text-white"}`}
          onClick={() => {
            setActiveTab("url");
            setValidationError(null);
          }}
        >
          Paste URL
          {activeTab === "url" && (
            <div className="absolute bottom-[-9px] left-0 right-0 h-0.5 bg-gradient-to-r from-primary to-accent" />
          )}
        </button>
      </div>

      {activeTab === "upload" ? (
        <div className="space-y-3">
          <div
            onClick={triggerFileInput}
            className="border-2 border-dashed border-primary/20 rounded-xl p-10 text-center hover:border-primary/50 transition-all duration-300 cursor-pointer bg-gradient-to-b from-primary/5 to-transparent hover:from-primary/10 group"
          >
            {fileName ? (
              <div className="flex flex-col items-center animate-in fade-in zoom-in-95">
                <div className="h-14 w-14 rounded-full bg-primary/20 flex items-center justify-center mx-auto mb-4">
                  <File className="h-6 w-6 text-primary" />
                </div>
                <p className="text-sm text-foreground font-semibold mb-1">{fileName}</p>
                <p className="text-xs text-primary font-medium">Click to change file</p>
              </div>
            ) : (
              <>
                <div className="h-14 w-14 rounded-full bg-primary/10 flex items-center justify-center mx-auto mb-4 group-hover:scale-110 group-hover:bg-primary/20 transition-all duration-300">
                  <Upload className="h-6 w-6 text-primary" />
                </div>
                <p className="text-sm text-foreground font-semibold">Drop your file here or click to browse</p>
                <p className="text-xs text-muted-foreground mt-1">Supports PDF, MP4, MP3, TXT up to 50MB</p>
              </>
            )}
          </div>
          {validationError && (
            <div className="text-red-500 text-xs font-semibold px-1 mt-2 animate-in fade-in slide-in-from-top-1 duration-200">
              {validationError}
            </div>
          )}
        </div>
      ) : (
        <div className="space-y-4 py-6">
          <div className="relative">
            <LinkIcon className="absolute left-4 top-1/2 -translate-y-1/2 h-4 w-4 text-primary/70" />
            <input
              type="text"
              placeholder="Paste YouTube video or document URL here..."
              value={url}
              onChange={(e) => {
                setUrl(e.target.value);
                setValidationError(null);
              }}
              className="w-full bg-white/5 border border-white/10 rounded-lg pl-12 pr-4 py-3 text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all placeholder:text-zinc-600"
            />
          </div>
          {validationError && (
            <div className="text-red-500 text-xs font-semibold px-1 animate-in fade-in slide-in-from-top-1 duration-200">
              {validationError}
            </div>
          )}
        </div>
      )}

      <div className="mt-6 flex flex-col items-center gap-4">
        {!isProcessing && !isDone && (
          <Button
            onClick={handleProcess}
            className="w-full sm:w-auto px-8 py-6 bg-gradient-to-r from-primary to-primary/80 hover:from-primary/90 hover:to-primary/70 text-white font-bold rounded-lg shadow-lg hover:shadow-primary/30 hover:-translate-y-0.5 transition-all duration-300"
          >
            <Zap className="mr-2 h-4 w-4 fill-white" />
            {buttonText}
          </Button>
        )}

        {isProcessing && (
          <div className="w-full space-y-3 -mt-2">
            <div className="flex justify-between text-sm font-medium">
              <span className="text-muted-foreground flex items-center gap-2">
                <div className="h-2 w-2 bg-primary rounded-full animate-pulse" />
                Analyzing content...
              </span>
              <span className="text-primary font-bold">{progress}%</span>
            </div>
            <div className="w-full h-2.5 bg-muted rounded-full overflow-hidden border border-border">
              <div className="h-full bg-gradient-to-r from-primary via-accent to-primary transition-all duration-100" style={{ width: `${progress}%` }} />
            </div>
          </div>
        )}

        {isDone && (
          <div className="flex items-center gap-2 text-emerald-500 font-bold text-sm animate-in zoom-in-95 duration-300">
            <div className="h-8 w-8 rounded-full bg-emerald-500/10 flex items-center justify-center">
              <CheckCircle2 className="h-5 w-5" />
            </div>
            Success! Redirecting to app dashboard...
          </div>
        )}
      </div>

      {/* Hidden File Input moved to bottom */}
      <input
        type="file"
        ref={fileInputRef}
        className="hidden"
        onChange={handleFileChange}
        accept=".pdf,.mp4,.mp3,.txt"
      />
    </div>
  )
}
