"use client";

import * as React from "react";
import { usePathname } from "next/navigation";
import { toast } from "sonner";
import { LifeBuoy, Loader2, Send } from "lucide-react";

import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useUserProfile } from "@/lib/user-profile";

export const OPEN_SUPPORT_MODAL_EVENT = "open-support-modal";

type Category = "bug" | "question" | "feature" | "billing" | "other";

const CATEGORY_OPTIONS: { value: Category; label: string; hint: string }[] = [
  { value: "bug", label: "Bug report", hint: "Something isn't working" },
  { value: "question", label: "Question", hint: "How do I…?" },
  { value: "feature", label: "Feature request", hint: "I wish Echo could…" },
  { value: "billing", label: "Billing", hint: "Plans, invoices, payment" },
  { value: "other", label: "Other", hint: "Anything else" },
];

const SUBJECT_MIN = 3;
const SUBJECT_MAX = 120;
const MESSAGE_MIN = 10;
const MESSAGE_MAX = 5000;

export function ContactSupportDialog() {
  const { profile, isAuthenticated } = useUserProfile();
  const pathname = usePathname();

  const [open, setOpen] = React.useState(false);
  const [category, setCategory] = React.useState<Category>("question");
  const [subject, setSubject] = React.useState("");
  const [message, setMessage] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);

  React.useEffect(() => {
    const handler = () => setOpen(true);
    window.addEventListener(OPEN_SUPPORT_MODAL_EVENT, handler);
    return () => window.removeEventListener(OPEN_SUPPORT_MODAL_EVENT, handler);
  }, []);

  React.useEffect(() => {
    if (!open) {
      setCategory("question");
      setSubject("");
      setMessage("");
      setSubmitting(false);
    }
  }, [open]);

  const canSubmit =
    subject.trim().length >= SUBJECT_MIN &&
    subject.trim().length <= SUBJECT_MAX &&
    message.trim().length >= MESSAGE_MIN &&
    message.trim().length <= MESSAGE_MAX &&
    !submitting;

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!canSubmit) return;

    setSubmitting(true);
    try {
      const pageUrl =
        typeof window !== "undefined"
          ? `${window.location.origin}${pathname || window.location.pathname}`
          : pathname || "";

      const res = await fetch("/api/support", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          subject: subject.trim(),
          category,
          message: message.trim(),
          pageUrl,
        }),
      });

      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        if (res.status === 429) {
          toast.error(
            data.error ||
              "You've submitted too many support requests. Please try again shortly."
          );
        } else if (res.status === 401) {
          toast.error("Please sign in to contact support.");
        } else {
          toast.error(
            data.error || "Couldn't send your message. Please try again."
          );
        }
        setSubmitting(false);
        return;
      }

      toast.success("Support request sent", {
        description:
          "We've received your message and will reply to " +
          (profile.email || "your email") +
          " shortly.",
      });
      setOpen(false);
    } catch (err) {
      console.error("[contact-support] submit failed", err);
      toast.error("Couldn't send your message. Please try again.");
      setSubmitting(false);
    }
  }

  if (!isAuthenticated) {
    // Fall back to mailto for logged-out users — the dialog depends on session.
    return null;
  }

  const selectedCategory = CATEGORY_OPTIONS.find((c) => c.value === category);

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <div className="flex items-center gap-2.5">
            <div className="flex size-8 items-center justify-center rounded-lg bg-primary/10 text-primary">
              <LifeBuoy className="size-4" />
            </div>
            <div className="flex-1">
              <DialogTitle>Contact support</DialogTitle>
              <DialogDescription>
                Our team will reply directly to{" "}
                <span className="font-medium text-foreground">
                  {profile.email || "your account email"}
                </span>
                .
              </DialogDescription>
            </div>
          </div>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-1.5">
            <Label htmlFor="support-category">What's this about?</Label>
            <Select
              value={category}
              onValueChange={(v) => v && setCategory(v as Category)}
            >
              <SelectTrigger id="support-category" className="w-full rounded-lg">
                <SelectValue placeholder="Select a category" />
              </SelectTrigger>
              <SelectContent>
                {CATEGORY_OPTIONS.map((opt) => (
                  <SelectItem key={opt.value} value={opt.value}>
                    <span className="font-medium">{opt.label}</span>
                    <span className="ml-1.5 text-xs text-muted-foreground">
                      {opt.hint}
                    </span>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-1.5">
            <Label htmlFor="support-subject">Subject</Label>
            <Input
              id="support-subject"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              placeholder={
                selectedCategory?.value === "bug"
                  ? "Short description of the bug"
                  : "One-line summary"
              }
              maxLength={SUBJECT_MAX}
              required
              autoComplete="off"
            />
          </div>

          <div className="space-y-1.5">
            <div className="flex items-center justify-between">
              <Label htmlFor="support-message">Message</Label>
              <span className="text-xs text-muted-foreground">
                {message.length}/{MESSAGE_MAX}
              </span>
            </div>
            <Textarea
              id="support-message"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              placeholder={
                category === "bug"
                  ? "What did you try? What happened? What did you expect?"
                  : "Share as much detail as you can."
              }
              maxLength={MESSAGE_MAX}
              className="min-h-32"
              required
            />
          </div>

          <div className="rounded-lg border border-border/50 bg-muted/30 px-3 py-2 text-xs text-muted-foreground">
            We'll attach your account details, current page, and browser info
            automatically so we can help faster.
          </div>

          <DialogFooter>
            <DialogClose
              render={
                <Button type="button" variant="outline" disabled={submitting} />
              }
            >
              Cancel
            </DialogClose>
            <Button type="submit" disabled={!canSubmit}>
              {submitting ? (
                <>
                  <Loader2 className="size-4 animate-spin" />
                  Sending…
                </>
              ) : (
                <>
                  <Send className="size-4" />
                  Send message
                </>
              )}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}

export function openContactSupport() {
  if (typeof window === "undefined") return;
  window.dispatchEvent(new CustomEvent(OPEN_SUPPORT_MODAL_EVENT));
}
