"use client";

import { useEffect, useRef, useState } from "react";
import {
  ExternalLink,
  Copy,
  Check,
  Calendar,
  Radio,
  X,
  Sparkles,
  AlertTriangle,
} from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { SimpleTooltip } from "@/components/ui/tooltip";
import type { AddMeetingResponseData } from "@/types/api";
import { startBot, abortMeeting } from "@/lib/api";
import { useMeetingsStore } from "@/store";
import { LogoIcon } from "@/components/ui/logo";

interface MeetingReadyDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  meeting: AddMeetingResponseData | null;
}

function PulsingDot() {
  return (
    <span className="relative flex h-2.5 w-2.5">
      <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75" />
      <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-green-500" />
    </span>
  );
}

export function MeetingReadyDialog({
  open,
  onOpenChange,
  meeting,
}: MeetingReadyDialogProps) {
  const [copied, setCopied] = useState(false);
  const [botLoading, setBotLoading] = useState(false);
  const [aborting, setAborting] = useState(false);

  // Track whether bot was successfully started in this session
  const botStartedRef = useRef(false);

  const deleteMeeting = useMeetingsStore((s) => s.deleteMeeting);
  const updateMeeting = useMeetingsStore((s) => s.updateMeeting);

  // Reset state every time dialog opens
  useEffect(() => {
    if (open) {
      setCopied(false);
      setBotLoading(false);
      setAborting(false);
      botStartedRef.current = false;
    }
  }, [open]);

  if (!meeting) return null;

  const handleCopyLink = () => {
    const text = meeting.meet_link;
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(text);
    } else {
      const el = document.createElement("textarea");
      el.value = text;
      el.style.position = "fixed";
      el.style.opacity = "0";
      document.body.appendChild(el);
      el.focus();
      el.select();
      document.execCommand("copy");
      document.body.removeChild(el);
    }
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const handleOpenMeet = async () => {
    setBotLoading(true);
    try {
      const res = await startBot(meeting.meeting_id);
      if (res.success) {
        botStartedRef.current = true; // mark bot as started
        window.open(meeting.meet_link, "_blank", "noopener,noreferrer");
        onOpenChange(false);
      }
    } catch (err) {
      console.error("Bot failed to join", err);
    } finally {
      setBotLoading(false);
    }
  };

  // Called when dialog is closed via X or backdrop click
  const handleClose = async () => {
    // If bot was already started — just close normally
    if (botStartedRef.current) {
      onOpenChange(false);
      return;
    }

    // Bot was NOT started — call abort API
    setAborting(true);
    try {
      const res = await abortMeeting(meeting.meeting_id);
      if (res.success) {
        // Remove from store so it doesn't show in the list
        deleteMeeting(String(meeting.meeting_id));
      } else {
        // Even if abort fails, update status locally to abort
        updateMeeting(String(meeting.meeting_id), { status: "abort" });
      }
    } catch {
      // Network error — still update locally so UI is consistent
      updateMeeting(String(meeting.meeting_id), { status: "abort" });
    } finally {
      setAborting(false);
      onOpenChange(false);
    }
  };

  const formattedDate = new Intl.DateTimeFormat("en-US", {
    weekday: "short",
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  }).format(new Date());

  return (
    <Dialog
      open={open}
      onOpenChange={(val) => {
        // Intercept close — run abort logic instead of closing directly
        if (!val) handleClose();
      }}
    >
      <DialogContent
        className="p-0 overflow-hidden max-w-md gap-0 border-0 shadow-2xl"
        hideClose
      >
        {/* Gradient header */}
        <div className="relative bg-gradient-to-br from-blue-600 via-blue-700 to-indigo-700 px-6 pt-8 pb-10">
          {/* Custom close button — triggers abort flow */}
          <SimpleTooltip content="Close and cancel meeting">
            <button
              onClick={handleClose}
              disabled={aborting || botLoading}
              className="absolute right-4 top-4 rounded-full p-1.5 text-white/70 hover:text-white hover:bg-white/10 transition-colors disabled:opacity-40"
              aria-label="Close"
            >
              {aborting ? (
                <span className="h-4 w-4 rounded-full border-2 border-white/30 border-t-white animate-spin block" />
              ) : (
                <X className="h-4 w-4" />
              )}
            </button>
          </SimpleTooltip>

          <div className="flex justify-center mb-4">
            <div className="relative">
              <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-white/15 backdrop-blur-sm border border-white/20">
                <LogoIcon size={36} />
              </div>
              <div className="absolute -top-1.5 -right-1.5 flex h-6 w-6 items-center justify-center rounded-full bg-green-400 border-2 border-white">
                <Sparkles className="h-3 w-3 text-white" />
              </div>
            </div>
          </div>

          <div className="text-center space-y-1">
            <DialogTitle className="text-xl font-bold text-white">
              Meeting Ready!
            </DialogTitle>
            <DialogDescription className="text-blue-200 text-sm">
              Your meeting has been set up and is ready to begin.
            </DialogDescription>
          </div>

          <div className="absolute bottom-0 left-0 right-0 h-5 bg-white dark:bg-gray-900 rounded-t-[20px]" />
        </div>

        {/* Body */}
        <div className="bg-white dark:bg-gray-900 px-6 pb-6 space-y-5">
          {/* Meeting info */}
          <div className="rounded-xl border border-gray-100 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50 p-4 space-y-3">
            <div className="flex items-start justify-between gap-2">
              <div className="min-w-0">
                <p className="text-xs text-gray-400 dark:text-gray-500 font-medium uppercase tracking-wide mb-0.5">
                  Meeting
                </p>
                <p className="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate">
                  {meeting.title}
                </p>
              </div>
              <Badge
                variant="default"
                className="shrink-0 flex items-center gap-1.5"
              >
                <PulsingDot />
                Scheduled
              </Badge>
            </div>

            <Separator />

            <div className="flex items-center gap-4 text-xs text-gray-500 dark:text-gray-400">
              <span className="flex items-center gap-1.5">
                <Calendar className="h-3.5 w-3.5 text-gray-400 dark:text-gray-500" />
                {formattedDate}
              </span>
              <span className="flex items-center gap-1.5">
                <Radio className="h-3.5 w-3.5 text-blue-500" />
                Ready to join
              </span>
            </div>

            {/* Meet link */}
            <div className="flex items-center gap-2 rounded-lg bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 px-3 py-2">
              <span className="text-xs text-gray-500 dark:text-gray-400 truncate flex-1 font-mono">
                {meeting.meet_link}
              </span>
              <SimpleTooltip
                content={copied ? "Copied to clipboard" : "Copy meet link"}
              >
                <button
                  onClick={handleCopyLink}
                  className="shrink-0 text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
                >
                  {copied ? (
                    <Check className="h-3.5 w-3.5 text-green-500" />
                  ) : (
                    <Copy className="h-3.5 w-3.5" />
                  )}
                </button>
              </SimpleTooltip>
            </div>
          </div>

          {/* Warning — closing without starting will abort */}
          <div className="flex items-start gap-2.5 rounded-xl border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-950/30 px-3.5 py-2.5">
            <AlertTriangle className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
            <p className="text-xs text-amber-700 dark:text-amber-400 leading-relaxed">
              Closing this dialog without clicking <strong>Open Meet</strong>{" "}
              will cancel the meeting.
            </p>
          </div>

          {/* What happens next */}
          <div className="space-y-2">
            <p className="text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wide">
              What happens next
            </p>
            <div className="space-y-2">
              {[
                { step: "1", text: "Join your Google Meet session" },
                { step: "2", text: "IIH Notetaker transcribes in real-time" },
                { step: "3", text: "AI summary generated when meeting ends" },
              ].map(({ step, text }) => (
                <div key={step} className="flex items-center gap-3">
                  <div className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-blue-50 dark:bg-blue-950 text-blue-600 dark:text-blue-400 text-[10px] font-bold">
                    {step}
                  </div>
                  <p className="text-sm text-gray-600 dark:text-gray-300">
                    {text}
                  </p>
                </div>
              ))}
            </div>
          </div>

          {/* Actions */}
          <div className="flex gap-2 pt-1">
            <SimpleTooltip content="Cancel this meeting">
              <Button
                variant="outline"
                className="flex-1"
                onClick={handleClose}
                disabled={aborting || botLoading}
              >
                {aborting ? "Cancelling…" : "Cancel Meeting"}
              </Button>
            </SimpleTooltip>
            <SimpleTooltip content="Start bot and open Google Meet">
              <Button
                className="flex-1 gap-2 bg-blue-600 hover:bg-blue-700"
                onClick={handleOpenMeet}
                disabled={botLoading || aborting}
              >
                {botLoading ? (
                  <span className="h-4 w-4 rounded-full border-2 border-white/30 border-t-white animate-spin" />
                ) : (
                  <ExternalLink className="h-4 w-4" />
                )}
                {botLoading ? "Starting…" : "Open Meet"}
              </Button>
            </SimpleTooltip>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
