"use client";
import React, { useState, useRef, useEffect } from "react";
import { motion } from "framer-motion";
import { Copy, Check, Send, Loader2 } from "lucide-react";
import contactData from "@/data/contact.json";

export default function ContactMe() {
  const [copied, setCopied] = useState(false);
  const [isMounted, setIsMounted] = useState(false);
  const [positionedTags, setPositionedTags] = useState<any[]>([]);
  const [status, setStatus] = useState<"idle" | "sending" | "success" | "error">("idle");
  const constraintsRef = useRef(null);

  // 1. Vyriešenie hydratácie a náhodného spawnu tagov z JSONu
  useEffect(() => {
    const randomized = contactData.tags.map((tag) => ({
      ...tag,
      initialX: Math.random() * 240 - 120, // Jemne zväčšený rozptyl
      initialY: Math.random() * 240 - 120,
      initialRotate: Math.random() * 40 - 20,
    }));
    
    setPositionedTags(randomized);
    setIsMounted(true);
  }, []);

  const copyToClipboard = () => {
    navigator.clipboard.writeText(contactData.config.to_email);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setStatus("sending");

    const formData = new FormData(e.currentTarget);
    const payload = {
      firstName: formData.get("firstName"),
      lastName: formData.get("lastName"),
      email: formData.get("email"),
      subject: formData.get("subject"),
      body: formData.get("body"),
    };

    try {
      const res = await fetch("/api/send", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      if (res.ok) {
        setStatus("success");
        (e.target as HTMLFormElement).reset();
        setTimeout(() => setStatus("idle"), 5000);
      } else {
        setStatus("error");
        setTimeout(() => setStatus("idle"), 5000);
      }
    } catch (err) {
      setStatus("error");
      setTimeout(() => setStatus("idle"), 5000);
    }
  };

  // Prevencia Hydration Mismatch
  if (!isMounted) return <div className="min-h-[650px] w-full" />;

  return (
    <section id="contact" className="max-w-7xl mx-auto px-8 py-24">
      <div className="bg-[#161618] border border-white/5 rounded-[40px] overflow-hidden grid grid-cols-1 lg:grid-cols-2 min-h-[650px] shadow-2xl">
        
        {/* L'AVÁ STRANA: Interaktívne Tagy */}
        <div 
          ref={constraintsRef} 
          className="relative bg-[#0d0d0d]/50 flex items-center justify-center overflow-hidden border-r border-white/5 p-12 touch-none"
        >
          {/* Dekoratívny text na pozadí */}
          <h2 className="absolute text-5xl md:text-7xl font-black text-white/[0.03] select-none text-center leading-none pointer-events-none uppercase tracking-tighter">
            Visual Studio <br /> Code
          </h2>
          
          {positionedTags.map((tag, i) => (
            <motion.div
              key={i}
              drag
              dragConstraints={constraintsRef}
              dragElastic={0.2}
              whileDrag={{ scale: 1.1, zIndex: 50 }}
              initial={{ 
                x: tag.initialX, 
                y: tag.initialY, 
                rotate: tag.initialRotate 
              }}
              className={`absolute cursor-grab active:cursor-grabbing px-6 py-3 rounded-full border text-sm font-bold shadow-2xl backdrop-blur-sm select-none ${tag.color}`}
            >
              {tag.name}
            </motion.div>
          ))}

          <p className="absolute bottom-6 text-[10px] uppercase tracking-[0.2em] text-gray-600 font-bold pointer-events-none">
            Drag them anywhere
          </p>
        </div>

        {/* PRAVÁ STRANA: Formulár */}
        <div className="p-8 md:p-14 flex flex-col justify-between bg-[#161618]">
          <div className="space-y-8">
            <div className="space-y-2">
              <h3 className="text-4xl font-black tracking-tighter text-white">Get in touch</h3>
              <p className="text-gray-400 font-medium">Have a project in mind? Let's build it.</p>
            </div>
            
            <form className="space-y-4" onSubmit={handleSubmit}>
              <div className="grid grid-cols-2 gap-4">
                <input name="firstName" required type="text" placeholder="First Name" className="bg-white/5 border border-white/10 rounded-2xl px-6 py-4 outline-none focus:border-blue-500/50 transition-all text-sm text-white" />
                <input name="lastName" required type="text" placeholder="Last Name" className="bg-white/5 border border-white/10 rounded-2xl px-6 py-4 outline-none focus:border-blue-500/50 transition-all text-sm text-white" />
              </div>
              <input name="email" required type="email" placeholder="E-mail" className="w-full bg-white/5 border border-white/10 rounded-2xl px-6 py-4 outline-none focus:border-blue-500/50 transition-all text-sm text-white" />
              <input name="subject" required type="text" placeholder="Subject" className="w-full bg-white/5 border border-white/10 rounded-2xl px-6 py-4 outline-none focus:border-blue-500/50 transition-all text-sm text-white" />
              <textarea name="body" required placeholder="How can I help?" rows={4} className="w-full bg-white/5 border border-white/10 rounded-2xl px-6 py-4 outline-none focus:border-blue-500/50 transition-all text-sm resize-none text-white" />
              
              <button 
                type="submit"
                disabled={status === "sending"}
                className={`btn-pill-primary w-full justify-center py-4 text-base group mt-2 transition-all flex items-center ${
                  status === "success" ? "bg-green-600 border-green-500 hover:bg-green-600" : 
                  status === "error" ? "bg-red-600 border-red-500 hover:bg-red-600" : ""
                }`}
              >
                {status === "idle" && (
                  <>
                    Send Message
                    <Send size={18} className="ml-2 group-hover:translate-x-1 group-hover:-translate-y-1 transition-transform" />
                  </>
                )}
                {status === "sending" && (
                  <>
                    <Loader2 size={18} className="mr-2 animate-spin" />
                    Sending...
                  </>
                )}
                {status === "success" && "Message Sent!"}
                {status === "error" && "Something went wrong..."}
              </button>
            </form>
          </div>

          <div className="mt-12 pt-8 border-t border-white/5 flex flex-col sm:flex-row items-center justify-between gap-4">
            <span className="text-gray-500 text-sm font-medium">Or {contactData.config.to_email}</span>
            <button 
              type="button"
              onClick={copyToClipboard}
              className="flex items-center gap-3 px-6 py-2.5 bg-white/5 hover:bg-white/10 border border-white/10 rounded-full text-xs font-bold transition-all active:scale-95 text-gray-300"
            >
              {copied ? (
                <> <Check size={14} className="text-green-500" /> Copied! </>
              ) : (
                <> <Copy size={14} /> Copy email </>
              )}
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}