import * as React from "react";
import {
  AlertTriangle,
  Mic,
  MicOff,
  Video,
  Volume2,
  VolumeX,
} from "lucide-react";
import { cn } from "@/lib/utils";
import {
  Card,
  CardTitle,
  CardDescription,
  CardFooter,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";

/**
 * CopilotMeetingRecordPrompt — WealthX DS (Molecule)
 *
 * Shown when the Copilot detects the broker is in a live meeting (Google Meet /
 * Microsoft Teams) and offers to record & summarize it. Lifecycle:
 *   suggested  → Start recording / Cancel
 *   recording  → Stop & summarize (with a live indicator + elapsed time)
 *   summarizing → spinner while notes are drafted
 * On completion the host surfaces a CopilotMeetingNoteCard.
 *
 * Pure display — the host detects the meeting tab and wires the callbacks.
 */

export type CopilotMeetingPlatform = "google-meet" | "teams" | "zoom";

export type CopilotMeetingRecordStatus =
  | "suggested"
  | "starting"
  | "recording"
  | "summarizing";

export type CopilotMeetingCaptureSurface = "browser" | "window" | "monitor";

export interface CopilotMeetingRecordPromptProps {
  /** Detected meeting platform — drives the caption label. */
  platform?: CopilotMeetingPlatform;
  /** Optional meeting title, e.g. "Meeting with Jordan Avery". */
  title?: string;
  /** Lifecycle state. Defaults to "suggested". */
  status?: CopilotMeetingRecordStatus;
  /** Elapsed time while recording, e.g. "02:14". */
  elapsedLabel?: string;
  /** suggested → begin recording. */
  onStartRecording?: () => void;
  /** Dismiss the prompt — shown on suggested, starting and summarizing. */
  onCancel?: () => void;
  /** recording → stop and summarize. */
  onStopRecording?: () => void;
  /** What the user actually shared — drives the source line and the mismatch warning. */
  captureSurface?: CopilotMeetingCaptureSurface;
  /** Best-effort name of the shared tab/window. Chrome does not always provide it. */
  captureLabel?: string;
  /** Shown when no sound is being picked up from the shared source or the mic. */
  audioWarning?: string;
  /** recording → reopen the share picker to swap the captured source. */
  onChangeTab?: () => void;
  /** Meeting audio is muted — that stretch is recorded as silence. */
  sourceAudioMuted?: boolean;
  /** Microphone is muted — that stretch is recorded as silence. */
  micMuted?: boolean;
  /** False once the mic could not be acquired; the toggle stays clickable to retry. */
  micAvailable?: boolean;
  /** recording → mute/unmute the shared tab or window audio. */
  onToggleSourceAudio?: () => void;
  /** recording → mute/unmute the broker's microphone. */
  onToggleMic?: () => void;
  startLabel?: string;
  cancelLabel?: string;
  stopLabel?: string;
  changeTabLabel?: string;
  className?: string;
}

const PLATFORM_LABEL: Record<CopilotMeetingPlatform, string> = {
  "google-meet": "Google Meet",
  teams: "Microsoft Teams",
  zoom: "Zoom",
};

const SURFACE_LABEL: Record<CopilotMeetingCaptureSurface, string> = {
  browser: "Browser tab",
  window: "Window",
  monitor: "Entire screen",
};

const SURFACE_MISMATCH_WARNING =
  "You shared your entire screen — this also captures other apps. Switch to the meeting tab or window.";

const MUTE_HINT = {
  both: "Paused — nothing is being recorded right now. The meeting still hears you.",
  source: "Meeting audio paused — only your microphone is being recorded.",
  mic: "Microphone paused — only the meeting audio is being recorded.",
} as const;

const RecordDot = (
  <span
    className="size-2 shrink-0 animate-pulse rounded-full bg-destructive"
    aria-hidden="true"
  />
);

const STATUS_COPY: Record<
  CopilotMeetingRecordStatus,
  { title: string; description: string }
> = {
  suggested: {
    title: "Record & summarize this meeting?",
    description:
      "I'll capture the conversation and draft notes with action items when it ends.",
  },
  starting: {
    title: "Choose the meeting source",
    description:
      "In the share dialog, pick the meeting tab or window and turn on the share-audio option, then Share.",
  },
  recording: {
    title: "Recording the meeting…",
    description: "I'll summarize when you stop.",
  },
  summarizing: {
    title: "Summarizing the meeting…",
    description: "Drafting notes and action items.",
  },
};

export function CopilotMeetingRecordPrompt({
  platform = "google-meet",
  title,
  status = "suggested",
  elapsedLabel,
  onStartRecording,
  onCancel,
  onStopRecording,
  captureSurface,
  captureLabel,
  audioWarning,
  onChangeTab,
  sourceAudioMuted = false,
  micMuted = false,
  micAvailable = true,
  onToggleSourceAudio,
  onToggleMic,
  startLabel = "Start recording",
  cancelLabel = "Cancel",
  stopLabel = "Stop & summarize",
  changeTabLabel = "Change source",
  className,
}: CopilotMeetingRecordPromptProps) {
  const platformLabel = PLATFORM_LABEL[platform];
  const warningText =
    audioWarning ??
    (captureSurface === "monitor" ? SURFACE_MISMATCH_WARNING : undefined);
  const hasToggles = Boolean(onToggleSourceAudio || onToggleMic);
  const sourceToggleLabel = sourceAudioMuted
    ? "Record the meeting audio again"
    : "Stop recording the meeting audio";
  const micToggleLabel = !micAvailable
    ? "Microphone unavailable — click to try again"
    : micMuted
      ? "Record my microphone again"
      : "Stop recording my microphone";
  const sourceToggleTooltip = sourceAudioMuted
    ? "Resume recording the meeting audio."
    : "Stop recording the meeting audio — everyone stays on the call, this only pauses what Copilot captures.";
  const micToggleTooltip = !micAvailable
    ? "Microphone unavailable — click to grant access, then your side gets recorded too."
    : micMuted
      ? "Resume recording your microphone."
      : "Stop recording your microphone — the meeting still hears you, this only pauses what Copilot captures.";
  const muteHint = sourceAudioMuted
    ? micMuted
      ? MUTE_HINT.both
      : MUTE_HINT.source
    : micMuted
      ? MUTE_HINT.mic
      : undefined;

  return (
    <Card className={cn("gap-2 py-3", className)}>
      <div className="flex flex-col gap-1 px-3">
        <span className="flex items-center gap-1.5 text-caption text-muted-foreground">
          {status === "recording" ? (
            <>
              {RecordDot}
              Recording · {platformLabel}
            </>
          ) : (
            <>
              <Video className="size-3" aria-hidden="true" />
              {status === "starting" ? platformLabel : `${platformLabel} detected`}
            </>
          )}
        </span>

        <CardTitle>{title ?? STATUS_COPY[status].title}</CardTitle>
        <div className="flex items-start gap-2">
          <CardDescription className="min-w-0 flex-1">
            {status === "recording" && elapsedLabel
              ? `Elapsed ${elapsedLabel} · ${STATUS_COPY.recording.description}`
              : STATUS_COPY[status].description}
          </CardDescription>
          {status === "recording" && hasToggles && (
            <div className="-mt-1 flex shrink-0 items-center gap-0.5">
              {onToggleSourceAudio && (
                <Tooltip>
                  <TooltipTrigger
                    render={
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon-xs"
                        onClick={onToggleSourceAudio}
                        aria-pressed={sourceAudioMuted}
                        aria-label={sourceToggleLabel}
                        className={cn(sourceAudioMuted && "text-destructive")}
                      />
                    }
                  >
                    {sourceAudioMuted ? <VolumeX /> : <Volume2 />}
                  </TooltipTrigger>
                  <TooltipContent side="top" className="max-w-56">
                    {sourceToggleTooltip}
                  </TooltipContent>
                </Tooltip>
              )}
              {onToggleMic && (
                <Tooltip>
                  <TooltipTrigger
                    render={
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon-xs"
                        onClick={onToggleMic}
                        aria-pressed={micMuted}
                        aria-label={micToggleLabel}
                        className={cn(micMuted && "text-destructive")}
                      />
                    }
                  >
                    {micMuted ? <MicOff /> : <Mic />}
                  </TooltipTrigger>
                  <TooltipContent side="top" className="max-w-56">
                    {micToggleTooltip}
                  </TooltipContent>
                </Tooltip>
              )}
            </div>
          )}
        </div>

        {status === "suggested" && (
          <p className="text-body-small text-muted-foreground">
            A share dialog will open — choose{" "}
            <span className="font-medium">the meeting tab or window</span> (your{" "}
            {platformLabel}), turn on{" "}
            <span className="font-medium">the share-audio option</span>, then
            Share so everyone is recorded.
          </p>
        )}

        {status === "recording" && captureSurface && (
          <span className="flex items-center gap-1.5 text-caption text-muted-foreground">
            <Volume2 className="size-3 shrink-0" aria-hidden="true" />
            <span className="truncate" title={captureLabel}>
              Recording audio from: {SURFACE_LABEL[captureSurface]}
              {captureLabel ? ` · ${captureLabel}` : ""}
            </span>
          </span>
        )}

        {status === "recording" && muteHint && (
          <span className="flex items-start gap-1.5 text-caption text-muted-foreground">
            <VolumeX className="mt-0.5 size-3 shrink-0" aria-hidden="true" />
            {muteHint}
          </span>
        )}

        {status === "recording" && warningText && (
          <span className="flex items-start gap-1.5 text-caption text-warning-text">
            <AlertTriangle className="mt-0.5 size-3 shrink-0" aria-hidden="true" />
            {warningText}
          </span>
        )}
      </div>

      {status === "suggested" && (onStartRecording || onCancel) && (
        <CardFooter className="gap-2 px-3">
          {onStartRecording && (
            <Button
              type="button"
              size="sm"
              onClick={onStartRecording}
              className="h-7"
            >
              {startLabel}
            </Button>
          )}
          {onCancel && (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={onCancel}
              className="h-7"
            >
              {cancelLabel}
            </Button>
          )}
        </CardFooter>
      )}

      {status === "starting" && (
        <CardFooter className="gap-2 px-3">
          <Button
            type="button"
            size="sm"
            variant="outline"
            disabled
            className="h-7 gap-1.5"
          >
            <Spinner size="sm" />
            Selecting tab…
          </Button>
          {onCancel && (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={onCancel}
              className="h-7"
            >
              {cancelLabel}
            </Button>
          )}
        </CardFooter>
      )}

      {status === "recording" && (onStopRecording || onChangeTab) && (
        <CardFooter className="gap-2 px-3">
          {onStopRecording && (
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={onStopRecording}
              className="h-7"
            >
              {stopLabel}
            </Button>
          )}
          {onChangeTab && (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={onChangeTab}
              className="h-7"
            >
              {changeTabLabel}
            </Button>
          )}
        </CardFooter>
      )}

      {status === "summarizing" && (
        <CardFooter className="gap-2 px-3">
          <Button
            type="button"
            size="sm"
            variant="outline"
            disabled
            className="h-7 gap-1.5"
          >
            <Spinner size="sm" />
            Summarizing…
          </Button>
          {onCancel && (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={onCancel}
              className="h-7"
            >
              {cancelLabel}
            </Button>
          )}
        </CardFooter>
      )}
    </Card>
  );
}
