import { useState, type FormEvent } from "react";
import {
  CheckCircle2Icon,
  MessageSquareWarningIcon,
  SendIcon,
} from "lucide-react";

import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { getSupabaseClient, type GlmUser } from "@/lib/supabase";
import { getAppSessionId } from "@/lib/wmc-backend";

const MAX_REPORT_LENGTH = 5000;

function getReportWebhookUrl() {
  const value = import.meta.env.VITE_REPORT_WEBHOOK_URL;
  return typeof value === "string" && value.trim()
    ? value.trim()
    : "https://agenteit.digitalcompass.agency/webhook/cotizador-wmc-reportar";
}

export function ReportIssueDialog({ user }: { user: GlmUser }) {
  const [open, setOpen] = useState(false);
  const [description, setDescription] = useState("");
  const [sending, setSending] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const [sent, setSent] = useState(false);

  const resetForm = () => {
    setDescription("");
    setSending(false);
    setErrorMessage("");
    setSent(false);
  };

  const handleOpenChange = (nextOpen: boolean) => {
    setOpen(nextOpen);
    if (nextOpen) resetForm();
  };

  const submitReport = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    const message = description.trim();
    if (!message) {
      setErrorMessage("Escribe la descripción del reporte antes de enviarlo.");
      return;
    }

    const webhookUrl = getReportWebhookUrl();
    if (!webhookUrl) {
      setErrorMessage(
        "El canal de reportes no está configurado. Contacta a IT para revisar VITE_REPORT_WEBHOOK_URL.",
      );
      return;
    }

    setSending(true);
    setErrorMessage("");

    try {
      const supabase = getSupabaseClient();
      const { data: { session }, error: sessionError } = await supabase.auth.getSession();
      if (sessionError || !session?.access_token) {
        throw new Error("Tu sesión expiró. Vuelve a iniciar sesión.");
      }

      const response = await fetch(webhookUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${session.access_token}`,
        },
        body: JSON.stringify({
          userEmail: user.email,
          userName: user.name,
          message,
          submittedAt: new Date().toISOString(),
          appSessionId: getAppSessionId(),
        }),
      });

      let result: { ok?: boolean; message?: string } | null = null;
      try {
        result = (await response.json()) as { ok?: boolean; message?: string };
      } catch {
        result = null;
      }

      if (!response.ok || result?.ok === false) {
        throw new Error(result?.message || "No se pudo enviar el reporte.");
      }

      setSent(true);
      setDescription("");
    } catch (error) {
      console.error("No se pudo enviar el reporte de usuario:", error);
      setErrorMessage(
        error instanceof Error && error.message
          ? error.message
          : "No se pudo enviar el reporte. Intenta nuevamente.",
      );
    } finally {
      setSending(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogTrigger asChild>
        <button
          type="button"
          aria-label="Reportar"
          title="Reportar"
          className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-border bg-card px-2.5 text-xs font-bold text-foreground transition-colors hover:bg-secondary sm:px-3"
        >
          <MessageSquareWarningIcon className="size-4" />
          <span className="hidden sm:inline">Reportar</span>
        </button>
      </DialogTrigger>

      <DialogContent className="overflow-hidden border-border bg-card p-0 sm:max-w-[32rem]">
        <div className="h-1 bg-brand" />
        <div className="p-6 pt-5">
          {sent ? (
            <div className="py-2 text-center">
              <div className="mx-auto grid size-12 place-items-center rounded-full bg-brand-soft text-brand">
                <CheckCircle2Icon className="size-6" />
              </div>
              <h2 className="mt-4 text-lg font-bold text-primary">Reporte enviado</h2>
              <p className="mx-auto mt-2 max-w-sm text-sm leading-relaxed text-muted-foreground">
                Tu reporte fue enviado correctamente al equipo de IT.
              </p>
              <button
                type="button"
                onClick={() => setOpen(false)}
                className="mt-5 inline-flex h-9 items-center justify-center rounded-lg bg-primary px-4 text-sm font-bold text-primary-foreground transition-colors hover:bg-primary/90"
              >
                Cerrar
              </button>
            </div>
          ) : (
            <form onSubmit={submitReport}>
              <DialogHeader className="gap-0">
                <div className="mb-2 grid size-10 place-items-center rounded-xl bg-brand-soft text-primary">
                  <MessageSquareWarningIcon className="size-5" />
                </div>
                <DialogTitle className="text-xl font-bold text-primary">Reporte</DialogTitle>
              </DialogHeader>

              <div className="mt-4">
                <label
                  htmlFor="report-description"
                  className="mb-2 block text-sm font-bold text-foreground"
                >
                  Descripción del Reporte <span className="text-destructive">*</span>
                </label>
                <Textarea
                  id="report-description"
                  value={description}
                  onChange={(event) => {
                    setDescription(event.target.value);
                    if (errorMessage) setErrorMessage("");
                  }}
                  maxLength={MAX_REPORT_LENGTH}
                  required
                  autoFocus
                  disabled={sending}
                  placeholder="Describe claramente lo que ocurrió, qué esperabas que pasara y cualquier detalle que pueda ayudar a revisarlo..."
                  className="min-h-36 resize-y rounded-xl bg-background px-3.5 py-3 leading-relaxed"
                />
                <div className="mt-1.5 flex items-center justify-between gap-3">
                  <p className="text-xs text-muted-foreground">
                    El reporte incluirá automáticamente tu nombre y correo.
                  </p>
                  <span className="shrink-0 text-[0.7rem] text-muted-foreground">
                    {description.length}/{MAX_REPORT_LENGTH}
                  </span>
                </div>

                {errorMessage ? (
                  <p role="alert" className="mt-3 text-sm leading-relaxed text-destructive">
                    {errorMessage}
                  </p>
                ) : null}
              </div>

              <DialogFooter className="mt-6 gap-2 sm:space-x-0">
                <button
                  type="button"
                  onClick={() => setOpen(false)}
                  disabled={sending}
                  className="inline-flex h-9 items-center justify-center rounded-lg border border-border bg-card px-4 text-sm font-bold text-foreground transition-colors hover:bg-secondary disabled:cursor-not-allowed disabled:opacity-50"
                >
                  Cancelar
                </button>
                <button
                  type="submit"
                  disabled={sending || !description.trim()}
                  className="inline-flex h-9 items-center justify-center gap-2 rounded-lg bg-primary px-4 text-sm font-bold text-primary-foreground transition-colors hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {sending ? (
                    <span className="size-4 animate-spin rounded-full border-2 border-primary-foreground/40 border-t-primary-foreground" />
                  ) : (
                    <SendIcon className="size-4" />
                  )}
                  {sending ? "Enviando..." : "Enviar reporte"}
                </button>
              </DialogFooter>
            </form>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}
