"use client"

import { useState, useEffect } from "react"
import { createPortal } from "react-dom"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { exportStyleguide } from "@/utils/export-styleguide"
import { Loader2, Check, X } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { useColorPalette } from "@/contexts/color-context"
import { useTheme } from "next-themes"

interface ExportPackagesOverlayProps {
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function ExportPackagesOverlay({ open, onOpenChange }: ExportPackagesOverlayProps) {
  const [exporting, setExporting] = useState(false)
  const [exportType, setExportType] = useState<"free" | "pro" | null>(null)
  const [exportError, setExportError] = useState<string | null>(null)
  const [email, setEmail] = useState("")
  const [mounted, setMounted] = useState(false)
  const { primaryColor } = useColorPalette()
  const { theme } = useTheme()

  useEffect(() => {
    setMounted(true)
  }, [])

  const handleExport = async (packageType: "free" | "pro") => {
    // For Starter Kit, require email
    if (packageType === "free" && !email.trim()) {
      setExportError("Please enter your email address to download the Starter Kit")
      return
    }

    // Basic email validation
    if (packageType === "free" && email.trim()) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(email.trim())) {
        setExportError("Please enter a valid email address")
        return
      }
    }

    setExportType(packageType)
    setExporting(true)
    setExportError(null)

    try {
      // Collect email for starter kit downloads
      if (packageType === "free") {
        const emailResponse = await fetch("/api/collect-email", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            email: email.trim(),
            packageType: "starter-kit",
          }),
        })

        if (!emailResponse.ok) {
          throw new Error("Failed to process email")
        }
      }

      await exportStyleguide({ packageType })

      setTimeout(() => {
        setExporting(false)
        setExportType(null)
      }, 2000)
    } catch (error) {
      console.error("Export failed:", error)
      setExporting(false)
      setExportType(null)
      setExportError(error instanceof Error ? error.message : "An unknown error occurred")
    }
  }

  if (!open || !mounted) return null

  const overlayContent = (
    <div className="fixed inset-0 z-[9999] flex items-center justify-center p-6">
      {/* Frosted Glass Background */}
      <div
        className={`absolute inset-0 backdrop-blur-2xl ${theme === "dark" ? "bg-black/15" : "bg-white/15"}`}
        onClick={() => onOpenChange(false)}
      />

      {/* Content - Just the cards */}
      <div className="relative z-10 w-full max-w-3xl">
        {exportError &&
          exportError !== "Please enter your email address to download the Starter Kit" &&
          exportError !== "Please enter a valid email address" && (
            <div className="bg-destructive/10 border border-destructive/20 text-destructive p-3 rounded-md text-sm mb-6 mx-auto">
              {exportError}
            </div>
          )}

        <div className="grid grid-cols-1 md:grid-cols-2 gap-10 justify-center">
          {/* Starter Kit */}
          <div className="border border-white/20 rounded-lg p-5 flex flex-col bg-background/95 backdrop-blur-sm shadow-lg h-full">
            <div className="mb-4">
              <div className="flex items-center justify-between mb-1">
                <h3 className="text-lg font-semibold tracking-tight">Starter Kit</h3>
                <Badge
                  variant="outline"
                  className="bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-950 dark:text-emerald-300 dark:border-emerald-800"
                >
                  Free
                </Badge>
              </div>
              <p className="text-sm text-muted-foreground">Perfect for learning and small projects</p>
            </div>

            <div className="space-y-4 mb-auto flex-grow">
              <div>
                <h4 className="text-sm font-medium text-foreground mb-2">What's included:</h4>
                <ul className="space-y-2">
                  <li className="flex items-start gap-2">
                    <Check className="h-4 w-4 text-emerald-500 mt-0.5 flex-shrink-0" />
                    <span className="text-sm text-foreground">Essential UI components (20+)</span>
                  </li>
                  <li className="flex items-start gap-2">
                    <Check className="h-4 w-4 text-emerald-500 mt-0.5 flex-shrink-0" />
                    <span className="text-sm text-foreground">Color system & typography</span>
                  </li>
                  <li className="flex items-start gap-2">
                    <Check className="h-4 w-4 text-emerald-500 mt-0.5 flex-shrink-0" />
                    <span className="text-sm text-foreground">Basic theming support</span>
                  </li>
                </ul>
              </div>

              <div>
                <h4 className="text-sm font-medium text-muted-foreground mb-2">Not included:</h4>
                <ul className="space-y-2">
                  <li className="flex items-start gap-2">
                    <X className="h-4 w-4 text-muted-foreground mt-0.5 flex-shrink-0" />
                    <span className="text-sm text-muted-foreground">Design controls</span>
                  </li>
                  <li className="flex items-start gap-2">
                    <X className="h-4 w-4 text-muted-foreground mt-0.5 flex-shrink-0" />
                    <span className="text-sm text-muted-foreground">Pre-built page blocks</span>
                  </li>
                </ul>
              </div>
            </div>

            <div className="space-y-3 mt-6">
              <Input
                type="email"
                placeholder="Enter your email address"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                error={
                  exportError === "Please enter your email address to download the Starter Kit" ||
                  exportError === "Please enter a valid email address"
                }
                className="w-full h-9 text-sm"
              />
              {(exportError === "Please enter your email address to download the Starter Kit" ||
                exportError === "Please enter a valid email address") && (
                <p className="text-sm text-destructive mt-1">{exportError}</p>
              )}
              <Button
                onClick={() => handleExport("free")}
                disabled={exporting}
                variant="outline"
                className="w-full h-9 text-sm"
              >
                {exporting && exportType === "free" ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Exporting...
                  </>
                ) : (
                  "Download Starter Kit"
                )}
              </Button>
            </div>
          </div>

          {/* Full Package */}
          <div className="border border-white/20 rounded-lg p-5 flex flex-col bg-background/95 backdrop-blur-sm shadow-lg h-full">
            <div className="mb-4">
              <div className="flex items-center justify-between mb-1">
                <h3 className="text-lg font-semibold tracking-tight">Full Package</h3>
                <Badge>Recommended</Badge>
              </div>
              <p className="text-sm text-muted-foreground">Complete solution for professional projects</p>
            </div>

            <div className="space-y-4 mb-auto flex-grow">
              <div>
                <h4 className="text-sm font-medium text-foreground mb-2">Everything in Starter Kit, plus:</h4>
                <ul className="space-y-2">
                  <li className="flex items-start gap-2">
                    <Check className="h-4 w-4 text-emerald-500 mt-0.5 flex-shrink-0" />
                    <span className="text-sm text-foreground">Complete component library (35+)</span>
                  </li>
                  <li className="flex items-start gap-2">
                    <Check className="h-4 w-4 text-emerald-500 mt-0.5 flex-shrink-0" />
                    <span className="text-sm text-foreground">Live design controls interface</span>
                  </li>
                  <li className="flex items-start gap-2">
                    <Check className="h-4 w-4 text-emerald-500 mt-0.5 flex-shrink-0" />
                    <span className="text-sm text-foreground">Pre-built page blocks & templates</span>
                  </li>
                  <li className="flex items-start gap-2">
                    <Check className="h-4 w-4 text-emerald-500 mt-0.5 flex-shrink-0" />
                    <span className="text-sm text-foreground">Material design system</span>
                  </li>
                </ul>
              </div>
            </div>

            <div className="mt-6">
              <Button onClick={() => handleExport("pro")} disabled={exporting} className="w-full h-9 text-sm">
                {exporting && exportType === "pro" ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Exporting...
                  </>
                ) : (
                  "Download Full Package"
                )}
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )

  return createPortal(overlayContent, document.body)
}
