"use client"

import { useState } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { Loader2, Check, Package, Sparkles, Share2 } from "lucide-react"
import type { AgentPackagePayload } from "@/lib/types"
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"

interface AgentForgeCardProps {
  payload: AgentPackagePayload
  onUseNow: (agentId: string) => void
  onPin: (agent: AgentPackagePayload, note?: string) => void
  onShare: (agentId: string) => void
}

export function AgentForgeCard({ payload, onUseNow, onPin, onShare }: AgentForgeCardProps) {
  const [isRevealed, setIsRevealed] = useState(false)
  const [showPinDialog, setShowPinDialog] = useState(false)
  const [pinNote, setPinNote] = useState("")
  const [shareClicked, setShareClicked] = useState(false)

  // Auto-reveal after mount
  useState(() => {
    const timer = setTimeout(() => setIsRevealed(true), 800)
    return () => clearTimeout(timer)
  })

  const handlePin = () => {
    onPin(payload, pinNote)
    setShowPinDialog(false)
    setPinNote("")
  }

  const handleShare = () => {
    onShare(payload.agentId)
    setShareClicked(true)
    setTimeout(() => setShareClicked(false), 2000)
  }

  if (!isRevealed) {
    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="relative overflow-hidden rounded-3xl border border-white/20 bg-gradient-to-br from-white/10 to-white/5 p-8 shadow-2xl backdrop-blur-xl"
      >
        {/* Shimmer background */}
        <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/10 to-transparent animate-shimmer" />
        
        <div className="relative flex flex-col items-center gap-6">
          <motion.div
            animate={{ rotate: 360 }}
            transition={{ duration: 2, repeat: Infinity, ease: "linear" }}
            className="flex h-16 w-16 items-center justify-center rounded-full bg-gradient-to-br from-burnt-orange to-terracotta shadow-lg"
          >
            <Package className="h-8 w-8 text-white" />
          </motion.div>

          <div className="text-center">
            <h3 className="font-heading text-2xl text-white/90">Forging your agent...</h3>
            <p className="mt-2 text-sm text-white/60">
              Morgan is packaging <span className="text-white/90">{payload.displayName}</span>
            </p>
          </div>

          {/* Progress steps */}
          <div className="flex w-full max-w-md flex-col gap-3">
            {["Gathering intent", "Synthesizing persona", "Sealing prompt"].map((step, i) => (
              <motion.div
                key={step}
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: i * 0.3 }}
                className="flex items-center gap-3 rounded-xl border border-white/10 bg-white/5 px-4 py-3"
              >
                <Loader2 className="h-4 w-4 animate-spin text-burnt-orange" />
                <span className="text-sm text-white/70">{step}</span>
              </motion.div>
            ))}
          </div>
        </div>
      </motion.div>
    )
  }

  return (
    <>
      <motion.div
        initial={{ opacity: 0, scale: 0.9 }}
        animate={{ opacity: 1, scale: 1 }}
        className="relative overflow-hidden rounded-3xl border border-white/25 bg-gradient-to-br from-white/20 to-white/10 shadow-2xl backdrop-blur-xl"
      >
        {/* Glow effect */}
        <div className="absolute -top-24 left-1/2 h-48 w-48 -translate-x-1/2 rounded-full bg-burnt-orange/20 blur-3xl" />

        <div className="relative p-8">
          {/* Header */}
          <div className="mb-6 flex items-start gap-4">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ type: "spring", duration: 0.6 }}
              className="flex h-16 w-16 shrink-0 items-center justify-center rounded-2xl bg-gradient-to-br from-burnt-orange to-terracotta text-3xl shadow-lg"
            >
              {payload.hints?.recommendedIcon || "🤖"}
            </motion.div>

            <div className="flex-1">
              <h3 className="font-heading text-3xl text-white">{payload.displayName}</h3>
              <p className="mt-2 text-base text-white/70">{payload.summary}</p>
              
              {/* Tags */}
              <div className="mt-3 flex flex-wrap gap-2">
                {payload.tags.map((tag) => (
                  <span
                    key={tag}
                    className="rounded-full border border-white/20 bg-white/10 px-3 py-1 text-xs uppercase tracking-wide text-white/80"
                  >
                    {tag}
                  </span>
                ))}
              </div>
            </div>
          </div>

          {/* Status badge */}
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
            className="mb-6 flex items-center gap-2 rounded-xl border border-accent/60 bg-accent/20 px-4 py-3"
          >
            <Check className="h-4 w-4 text-accent-foreground" />
            <span className="text-sm font-medium text-accent-foreground">Prompt secured</span>
            <Sparkles className="ml-auto h-4 w-4 text-accent-foreground" />
          </motion.div>

          {/* Actions */}
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.3 }}
            className="flex flex-col gap-3 sm:flex-row"
          >
            <Button
              onClick={() => onUseNow(payload.agentId)}
              className="flex-1 rounded-2xl bg-gradient-to-r from-burnt-orange to-terracotta text-base font-medium text-white shadow-lg transition-all hover:scale-105 hover:shadow-xl"
              size="lg"
            >
              Use now
            </Button>

            <Button
              onClick={() => setShowPinDialog(true)}
              variant="outline"
              className="flex-1 rounded-2xl border-white/30 bg-white/10 text-base font-medium text-white backdrop-blur-sm transition-all hover:bg-white/20 hover:scale-105"
              size="lg"
            >
              Pin for later
            </Button>

            <Button
              onClick={handleShare}
              variant="outline"
              className="rounded-2xl border-white/30 bg-white/10 backdrop-blur-sm transition-all hover:bg-white/20 hover:scale-105"
              size="lg"
            >
              {shareClicked ? (
                <Check className="h-5 w-5 text-white" />
              ) : (
                <Share2 className="h-5 w-5 text-white" />
              )}
            </Button>
          </motion.div>

          {/* When to use hint */}
          {payload.hints?.whenToUse && (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.4 }}
              className="mt-4 rounded-xl border border-white/10 bg-white/5 px-4 py-3"
            >
              <p className="text-sm text-white/60">
                <span className="font-medium text-white/80">When to use:</span>{" "}
                {payload.hints.whenToUse}
              </p>
            </motion.div>
          )}
        </div>
      </motion.div>

      {/* Pin dialog */}
      <Dialog open={showPinDialog} onOpenChange={setShowPinDialog}>
        <DialogContent className="palette-shell">
          <DialogHeader>
            <DialogTitle className="font-heading text-2xl">Pin agent</DialogTitle>
            <DialogDescription>
              Add an optional note to help you remember when to use {payload.displayName}.
            </DialogDescription>
          </DialogHeader>

          <div className="mt-4 space-y-4">
            <Input
              placeholder="e.g., For research tasks requiring citations"
              value={pinNote}
              onChange={(e) => setPinNote(e.target.value)}
              className="rounded-xl border-white/20 bg-white/10 text-white placeholder:text-white/40"
            />

            <div className="flex gap-3">
              <Button
                onClick={handlePin}
                className="flex-1 rounded-xl bg-gradient-to-r from-burnt-orange to-terracotta"
              >
                Pin agent
              </Button>
              <Button
                onClick={() => setShowPinDialog(false)}
                variant="outline"
                className="flex-1 rounded-xl border-white/30"
              >
                Cancel
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  )
}

