"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { siteConfig } from "@/lib/data"
import { MessageSquare, Star, Send, CheckCircle2 } from "lucide-react"
import { cn } from "@/lib/utils"

export function FeedbackSection({ className, theme = "light" }: { className?: string; theme?: "light" | "dark" }) {
  const isDark = theme === "dark"
  const [formState, setFormState] = useState({
    name: "",
    email: "",
    type: "general",
    tool: "all",
    rating: 0,
    message: ""
  })
  const [hoverRating, setHoverRating] = useState(0)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [submitted, setSubmitted] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsSubmitting(true)
    
    // Validate Rating
    if (formState.rating === 0) {
      alert("Please select a star rating before submitting.");
      setIsSubmitting(false);
      return;
    }

    try {
      // Send to local API route
      const response = await fetch("/api/feedback", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify({
          name: formState.name,
          email: formState.email,
          type: formState.type,
          tool: formState.tool,
          rating: formState.rating,
          message: formState.message,
        }),
      });

      const result = await response.json();
      if (response.ok && result.success) {
        setSubmitted(true);
        setFormState({ name: "", email: "", type: "general", tool: "all", rating: 0, message: "" });
        setTimeout(() => setSubmitted(false), 4000);
      } else {
        alert("Something went wrong! Please try again.");
      }
    } catch (error) {
      alert("Network error. Please try again later.");
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <section id="feedback" className={cn(
      "pt-0 pb-8 sm:pb-10 relative overflow-hidden",
      isDark 
        ? "bg-[#0F172A] text-white" 
        : "bg-background text-foreground",
      className
    )}>
      {/* Background Decorative Element */}
      <div className={cn(
        "absolute bottom-0 right-0 translate-y-1/4 translate-x-1/4 w-96 h-96 rounded-full blur-3xl -z-10",
        isDark ? "bg-primary/10" : "bg-primary/5"
      )} />
      
      <div className="mx-auto max-w-4xl px-4 lg:px-8 relative">
        <div className="text-center mb-8 flex flex-col items-center">
          <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-primary/10 text-primary text-sm font-bold uppercase tracking-wider mb-4 border border-primary/20">
            <MessageSquare className="h-4 w-4" />
            User Feedback
          </div>
          <h2 className={cn("text-2xl sm:text-3xl font-bold text-balance tracking-tight", isDark ? "text-white" : "text-foreground")}>
            Help us improve CodeframeAI
          </h2>
          <p className={cn("mt-4 text-base max-w-2xl text-pretty", isDark ? "text-zinc-400" : "text-muted-foreground")}>
            Your feedback shapes the future of our platform. Let us know what you love, what you'd like to see next, or if you've encountered any issues.
          </p>
        </div>

        <form onSubmit={handleSubmit} className={cn(
          "border rounded-2xl p-6 sm:p-8 transition-colors shadow-lg",
          isDark 
            ? "bg-white/5 border-white/10" 
            : "bg-card border-border shadow-primary/5"
        )}>
          {/* Star Rating Section */}
          <div className="mb-6 flex flex-col items-center">
            <label className={cn("block text-sm font-medium mb-3", isDark ? "text-zinc-300" : "text-foreground")}>
              How would you rate your experience? *
            </label>
            <div className="flex gap-2">
              {[1, 2, 3, 4, 5].map((star) => (
                <button
                  type="button"
                  key={star}
                  onClick={() => setFormState({ ...formState, rating: star })}
                  onMouseEnter={() => setHoverRating(star)}
                  onMouseLeave={() => setHoverRating(0)}
                  className="focus:outline-none transition-transform hover:scale-110 active:scale-95"
                >
                  <Star 
                    className={cn(
                      "h-8 w-8 transition-colors duration-200", 
                      (hoverRating || formState.rating) >= star 
                        ? "fill-yellow-400 text-yellow-400" 
                        : isDark ? "text-zinc-600 fill-zinc-800" : "text-zinc-300 fill-zinc-100"
                    )} 
                  />
                </button>
              ))}
            </div>
          </div>

          <div className="grid sm:grid-cols-2 gap-4 mb-4">
            <div>
              <label htmlFor="name" className={cn("block text-sm font-medium mb-2", isDark ? "text-zinc-300" : "text-muted-foreground")}>
                Your Name
              </label>
              <input
                type="text"
                id="name"
                required
                value={formState.name}
                onChange={(e) => setFormState({ ...formState, name: e.target.value })}
                className={cn(
                  "w-full px-4 py-3 rounded-lg border focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all",
                  isDark 
                    ? "border-white/10 bg-white/5 text-white placeholder:text-zinc-600 focus:border-primary" 
                    : "border-border bg-background text-foreground placeholder:text-muted-foreground/60 focus:border-primary"
                )}
                placeholder="John Doe"
              />
            </div>
            <div>
              <label htmlFor="email" className={cn("block text-sm font-medium mb-2", isDark ? "text-zinc-300" : "text-muted-foreground")}>
                Your Email
              </label>
              <input
                type="email"
                id="email"
                required
                value={formState.email}
                onChange={(e) => setFormState({ ...formState, email: e.target.value })}
                className={cn(
                  "w-full px-4 py-3 rounded-lg border focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all",
                  isDark 
                    ? "border-white/10 bg-white/5 text-white placeholder:text-zinc-600 focus:border-primary" 
                    : "border-border bg-background text-foreground placeholder:text-muted-foreground/60 focus:border-primary"
                )}
                placeholder="john@example.com"
              />
            </div>
          </div>

          <div className="grid sm:grid-cols-2 gap-4 mb-4">
            <div>
              <label htmlFor="type" className={cn("block text-sm font-medium mb-2", isDark ? "text-zinc-300" : "text-muted-foreground")}>
                Feedback Type
              </label>
              <select
                id="type"
                value={formState.type}
                onChange={(e) => setFormState({ ...formState, type: e.target.value })}
                className={cn(
                  "w-full px-4 py-3 rounded-lg border focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all appearance-none",
                  isDark 
                    ? "border-white/10 bg-white/5 text-white focus:border-primary" 
                    : "border-border bg-background text-foreground focus:border-primary"
                )}
              >
                <option value="general">General Feedback</option>
                <option value="feature">Feature Request</option>
                <option value="bug">Bug Report</option>
                <option value="praise">Praise</option>
              </select>
            </div>
            <div>
              <label htmlFor="tool" className={cn("block text-sm font-medium mb-2", isDark ? "text-zinc-300" : "text-muted-foreground")}>
                Which Tool?
              </label>
              <select
                id="tool"
                value={formState.tool}
                onChange={(e) => setFormState({ ...formState, tool: e.target.value })}
                className={cn(
                  "w-full px-4 py-3 rounded-lg border focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all appearance-none",
                  isDark 
                    ? "border-white/10 bg-white/5 text-white focus:border-primary" 
                    : "border-border bg-background text-foreground focus:border-primary"
                )}
              >
                <option value="all">General / Entire Platform</option>
                <option value="mindmap">AI Mindmap Generator</option>
                <option value="summary">AI Summary Generator</option>
                <option value="video">AI Video Summarizer</option>
                <option value="pdf">AI PDF Summarizer</option>
                <option value="legal">AI Legal Document Analysis</option>
              </select>
            </div>
          </div>

          <div className="mb-6">
            <label htmlFor="message" className={cn("block text-sm font-medium mb-2", isDark ? "text-zinc-300" : "text-muted-foreground")}>
              Detailed Feedback *
            </label>
            <textarea
              id="message"
              required
              rows={5}
              value={formState.message}
              onChange={(e) => setFormState({ ...formState, message: e.target.value })}
              className={cn(
                "w-full px-4 py-3 rounded-lg border focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all resize-none",
                isDark 
                  ? "border-white/10 bg-white/5 text-white placeholder:text-zinc-600 focus:border-primary" 
                  : "border-border bg-background text-foreground placeholder:text-muted-foreground/60 focus:border-primary"
              )}
              placeholder="Tell us what's on your mind..."
            />
          </div>

          <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
            <Button 
              type="submit" 
              disabled={isSubmitting} 
              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"
            >
              {isSubmitting ? (
                "Submitting..."
              ) : (
                <>
                  Submit Feedback <Send className="ml-2 h-4 w-4" />
                </>
              )}
            </Button>

            {submitted && (
              <div className="w-full sm:w-auto px-4 py-3 rounded-lg bg-emerald-500/10 border border-emerald-500/20 text-emerald-500 font-medium flex items-center justify-center gap-2 animate-in fade-in slide-in-from-bottom-2">
                <CheckCircle2 className="h-5 w-5" />
                Feedback received! Thank you.
              </div>
            )}
          </div>
        </form>
      </div>
    </section>
  )
}
