"use client"

import { useState, useRef, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { LinkIcon, Upload, Zap, CheckCircle2, File } from "lucide-react"
import { getApiUrl } from "@/lib/env"
import { trackEvent } from "@/utils/analytics"

interface HeroInputTabProps {
  buttonText?: string;
}

export function HeroInputTab({ buttonText = "Analyze" }: HeroInputTabProps) {
  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 [validationError, setValidationError] = useState<string | null>(null)

  const fileInputRef = useRef<HTMLInputElement>(null)

  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
    }

    trackEvent('analyze_click', { type: activeTab === 'upload' ? 'file' : 'url', location: 'hero_input' });

    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}/#/analyze-public?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}/#/analyze-public?source=external&type=video_link&url=${encodeURIComponent(url)}`
      }

      const interval = setInterval(() => {
        setProgress((prev) => {
          if (prev >= 100) {
            clearInterval(interval)
            setIsProcessing(false)
            setIsDone(true)

            setTimeout(() => {
              window.location.href = redirectUrl
            }, 1000)

            return 100
          }
          return prev + 10
        })
      }, 80)
    } catch (error) {
      console.error("Error processing:", error)
      setValidationError("An error occurred during 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()
  }



  return (
    <div className="w-full max-w-2xl mx-auto mt-6 bg-card/60 backdrop-blur-xl border border-border/60 rounded-2xl shadow-[0_8px_30px_rgb(0,0,0,0.04)] p-4 sm:p-5 transition-all duration-300 relative z-10">
      
      {/* Tabs */}
      <div className="flex justify-center gap-6 mb-4">
        <button
          className={`text-sm font-semibold transition-all relative pb-1 ${activeTab === "upload" ? "text-primary" : "text-muted-foreground hover:text-foreground"}`}
          onClick={() => {
            setActiveTab("upload");
            setValidationError(null);
          }}
        >
          Upload File
          {activeTab === "upload" && (
            <div className="absolute bottom-0 left-0 right-0 h-[2px] bg-primary rounded-full" />
          )}
        </button>
        <button
          className={`text-sm font-semibold transition-all relative pb-1 ${activeTab === "url" ? "text-primary" : "text-muted-foreground hover:text-foreground"}`}
          onClick={() => {
            setActiveTab("url");
            setValidationError(null);
          }}
        >
          Paste URL
          {activeTab === "url" && (
            <div className="absolute bottom-0 left-0 right-0 h-[2px] bg-primary rounded-full" />
          )}
        </button>
      </div>

      {/* Content Area */}
      <div className="flex flex-col gap-2">
        {!isProcessing && !isDone ? (
          <div className="flex flex-col sm:flex-row gap-3 items-start sm:items-center">
            {activeTab === "upload" ? (
              <div
                onClick={triggerFileInput}
                className="flex-grow w-full border border-dashed border-primary/30 rounded-xl px-4 py-2.5 flex items-center justify-between hover:border-primary/50 hover:bg-primary/5 transition-all cursor-pointer bg-background/50 h-[48px]"
              >
                <div className="flex items-center gap-3 overflow-hidden w-full">
                  <div className="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center shrink-0">
                    {fileName ? <File className="h-4 w-4 text-primary" /> : <Upload className="h-4 w-4 text-primary" />}
                  </div>
                  <div className="truncate text-left w-full">
                    {fileName ? (
                      <p className="text-sm font-medium text-foreground truncate">{fileName}</p>
                    ) : (
                      <p className="text-sm text-muted-foreground truncate">Drop file or click to browse</p>
                    )}
                  </div>
                </div>
              </div>
            ) : (
              <div className="relative flex-grow w-full h-[48px]">
                <LinkIcon className="absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <input
                  type="text"
                  placeholder="Paste YouTube or document URL..."
                  value={url}
                  onChange={(e) => {
                    setUrl(e.target.value);
                    setValidationError(null);
                  }}
                  className="w-full h-full bg-background/50 border border-border/80 rounded-xl pl-11 pr-4 text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/50 transition-all placeholder:text-muted-foreground"
                />
              </div>
            )}

            <Button 
              onClick={handleProcess} 
              className="w-full sm:w-auto shrink-0 h-[48px] rounded-xl px-6 bg-primary text-primary-foreground font-semibold shadow-md hover:shadow-lg transition-all"
            >
              <Zap className="mr-2 h-4 w-4" />
              {buttonText}
            </Button>
          </div>
        ) : isProcessing ? (
          <div className="flex items-center gap-4 w-full h-[48px] px-3 bg-background/40 rounded-xl border border-border/50">
            <div className="text-sm font-medium text-muted-foreground flex items-center gap-2 whitespace-nowrap">
              <div className="h-2 w-2 bg-primary rounded-full animate-pulse" />
              Analyzing...
            </div>
            <div className="flex-grow h-2 bg-muted rounded-full overflow-hidden">
              <div className="h-full bg-primary transition-all duration-100 ease-linear" style={{ width: `${progress}%` }} />
            </div>
            <div className="text-sm font-bold text-primary w-9 text-right">{progress}%</div>
          </div>
        ) : (
          <div className="flex items-center justify-center gap-2 w-full h-[48px] text-emerald-600 dark:text-emerald-500 font-medium text-sm bg-emerald-500/10 rounded-xl border border-emerald-500/20 animate-in zoom-in-95 duration-300">
            <CheckCircle2 className="h-5 w-5" />
            Success! Redirecting...
          </div>
        )}

        {validationError && (
          <div className="text-red-500 text-xs font-medium pl-1 animate-in fade-in slide-in-from-top-1">
            {validationError}
          </div>
        )}
      </div>

      <input
        type="file"
        ref={fileInputRef}
        className="hidden"
        onChange={handleFileChange}
        accept=".pdf,.mp4,.mp3,.txt"
      />
    </div>
  )
}
