"use client";

import { useState, useRef, useCallback } from "react";
import { Bug, Camera, X, Send, CheckCircle2 } from "lucide-react";

export function FeedbackWidget() {
  const [open, setOpen] = useState(false);
  const [type, setType] = useState<"bug" | "feedback" | "question">("bug");
  const [description, setDescription] = useState("");
  const [screenshot, setScreenshot] = useState<string | null>(null);
  const [screenshotFile, setScreenshotFile] = useState<File | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setScreenshotFile(file);
      setScreenshot(URL.createObjectURL(file));
    }
  };

  const handlePaste = useCallback((e: React.ClipboardEvent) => {
    const items = e.clipboardData?.items;
    if (!items) return;
    for (const item of Array.from(items)) {
      if (item.type.startsWith("image/")) {
        const file = item.getAsFile();
        if (file) {
          setScreenshotFile(file);
          setScreenshot(URL.createObjectURL(file));
        }
      }
    }
  }, []);

  const handleSubmit = async () => {
    if (!description.trim()) return;
    setSubmitting(true);
    try {
      const formData = new FormData();
      formData.append("type", type);
      formData.append("description", description);
      formData.append("url", window.location.href);
      formData.append("userAgent", navigator.userAgent);
      formData.append("viewport", `${window.innerWidth}x${window.innerHeight}`);
      if (screenshotFile) formData.append("screenshot", screenshotFile);
      await fetch("/api/feedback", { method: "POST", body: formData });
      setSubmitted(true);
      setTimeout(() => { setOpen(false); setSubmitted(false); setDescription(""); setScreenshot(null); setScreenshotFile(null); }, 2000);
    } catch { /* silent */ }
    setSubmitting(false);
  };

  return (
    <>
      <button
        onClick={() => setOpen(true)}
        className="fixed bottom-24 right-6 z-40 w-10 h-10 rounded-full bg-slate-800 text-white shadow-lg hover:bg-slate-700 flex items-center justify-center transition-all hover:scale-110"
        title="Report an issue"
      >
        <Bug className="w-5 h-5" />
      </button>

      {open && (
        <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4">
          <div className="fixed inset-0 bg-black/40" onClick={() => setOpen(false)} />
          <div className="relative bg-white rounded-xl shadow-2xl w-full max-w-md overflow-hidden" onPaste={handlePaste}>
            <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
              <h3 className="font-semibold text-slate-900">Report an Issue</h3>
              <button onClick={() => setOpen(false)} className="text-slate-400 hover:text-slate-600"><X className="w-5 h-5" /></button>
            </div>

            {submitted ? (
              <div className="p-8 text-center">
                <CheckCircle2 className="w-12 h-12 text-green-500 mx-auto mb-3" />
                <p className="font-semibold text-slate-900">Thanks for the report!</p>
                <p className="text-sm text-slate-500 mt-1">We&apos;ll look into this right away.</p>
              </div>
            ) : (
              <div className="p-5 space-y-4">
                <div>
                  <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Type</p>
                  <div className="flex gap-2">
                    {(["bug", "feedback", "question"] as const).map((t) => (
                      <button
                        key={t}
                        onClick={() => setType(t)}
                        className={`px-3 py-1.5 rounded-lg text-xs font-semibold transition ${
                          type === t
                            ? t === "bug" ? "bg-red-50 text-red-700 ring-1 ring-red-200"
                              : t === "feedback" ? "bg-blue-50 text-blue-700 ring-1 ring-blue-200"
                              : "bg-violet-50 text-violet-700 ring-1 ring-violet-200"
                            : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                        }`}
                      >
                        {t === "bug" ? "Bug" : t === "feedback" ? "Feedback" : "Question"}
                      </button>
                    ))}
                  </div>
                </div>

                <div>
                  <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">What happened?</p>
                  <textarea
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder={type === "bug" ? "Describe what you expected vs what happened..." : type === "feedback" ? "How can we improve this?" : "What do you need help with?"}
                    rows={4}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 resize-none"
                  />
                </div>

                <div>
                  <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Screenshot (optional)</p>
                  {screenshot ? (
                    <div className="relative group">
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img src={screenshot} alt="Screenshot" className="rounded-lg border border-slate-200 max-h-40 w-full object-cover" />
                      <button onClick={() => { setScreenshot(null); setScreenshotFile(null); }} className="absolute top-2 right-2 w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition"><X className="w-3 h-3" /></button>
                    </div>
                  ) : (
                    <button onClick={() => fileRef.current?.click()} className="flex items-center gap-2 px-3 py-2 border border-dashed border-slate-300 rounded-lg text-xs text-slate-500 hover:border-slate-400 hover:text-slate-700 transition w-full justify-center">
                      <Camera className="w-4 h-4" /> Upload or paste screenshot
                    </button>
                  )}
                  <input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFileSelect} />
                  <p className="text-[10px] text-slate-400 mt-1">Tip: screenshot then paste (Cmd+V)</p>
                </div>

                <div className="bg-slate-50 rounded-lg px-3 py-2 text-[10px] text-slate-400">
                  Auto-captured: page URL, browser, viewport, timestamp
                </div>

                <button
                  onClick={handleSubmit}
                  disabled={!description.trim() || submitting}
                  className="w-full py-2.5 rounded-lg bg-brand-600 text-white font-semibold text-sm hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 transition"
                >
                  {submitting ? "Submitting..." : <><Send className="w-4 h-4" /> Submit Report</>}
                </button>
              </div>
            )}
          </div>
        </div>
      )}
    </>
  );
}
