import { type ReactElement } from "react";
import { cn } from "@/lib/utils";
import { Badge } from "./badge";
import { Button } from "./button";
import { Input } from "./input";
import { Separator } from "./separator";
import { Check, Copy, ExternalLink, Link2, Mail, Settings } from "lucide-react";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export type EmailProvider = "gmail" | "outlook";

export interface GmailConnection {
  connected: boolean;
  email?: string;
  /** ISO date string — "2026-03-15" */
  connectedAt?: string;
}

export interface AppointmentGmailConnectProps {
  /**
   * Email provider that is connected. Determines displayed labels.
   * Defaults to "gmail".
   */
  provider?: EmailProvider;
  /** Email connection state sourced from Settings > Integrations */
  connection: GmailConnection;
  /** Booking link to display when connected */
  calendarLink?: string;
  /** Highlights the card with a primary-colored border — used when this provider matches the default meeting platform. */
  highlighted?: boolean;
  /** Called when user clicks the copy button next to the calendar link */
  onCopyLink?: () => void;
  /** Called when user clicks "Go to Integrations" */
  onGoToIntegrations?: () => void;
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

function GmailIcon({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 24 24" className={className} aria-hidden="true">
      <path
        fill="#EA4335"
        d="M24 5.457v13.909c0 .904-.732 1.636-1.636 1.636h-3.819V11.73L12 16.64l-6.545-4.91v9.273H1.636A1.636 1.636 0 0 1 0 19.366V5.457c0-2.023 2.309-3.178 3.927-1.964L5.455 4.64 12 9.548l6.545-4.91 1.528-1.145C21.69 2.28 24 3.434 24 5.457z"
      />
    </svg>
  );
}

function OutlookIcon({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 24 24" className={className} aria-hidden="true">
      <path
        fill="#0078D4"
        d="M0 3.449L9.75 2.1v9.451H0m10.949-9.602L24 0v11.4H10.949M0 12.6h9.75v9.451L0 20.699M10.949 12.6H24V24l-12.9-1.801"
      />
    </svg>
  );
}

type IconComponent = (props: { className?: string }) => ReactElement;

const PROVIDER_META: Record<
  EmailProvider,
  { label: string; iconBg: string; Icon: IconComponent }
> = {
  gmail: { label: "Gmail", iconBg: "bg-[#EA4335]/10", Icon: GmailIcon },
  outlook: { label: "Outlook", iconBg: "bg-[#0078D4]/10", Icon: OutlookIcon },
};

const PERMISSIONS = [
  "Read your calendar availability",
  "Send appointment confirmation emails",
  "Create calendar events on your behalf",
];

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

export function AppointmentGmailConnect({
  provider = "gmail",
  connection,
  calendarLink,
  highlighted = false,
  onCopyLink,
  onGoToIntegrations,
}: AppointmentGmailConnectProps) {
  const { label, iconBg, Icon } = PROVIDER_META[provider];

  if (connection.connected) {
    return (
      <div
        className={cn(
          "flex flex-col border bg-card",
          highlighted ? "border-primary" : "border-border"
        )}
      >
        {/* Header */}
        <div className="flex items-start gap-3 px-5 py-4">
          <div
            className={cn(
              "flex h-10 w-10 shrink-0 items-center justify-center",
              iconBg
            )}
          >
            <Icon className="h-5 w-5" />
          </div>
          <div className="min-w-0 flex-1">
            <p className="text-base font-semibold">{label} Connected</p>
            <p className="truncate text-sm text-muted-foreground">
              {connection.email}
            </p>
          </div>
          <div className="flex shrink-0 flex-col items-end gap-1.5">
            <Button
              size="sm"
              variant="ghost"
              className="gap-1.5 text-muted-foreground"
              onClick={onGoToIntegrations}
            >
              <Settings className="h-3.5 w-3.5" />
              Manage
            </Button>
            <div className="flex items-center gap-2">
              <Badge variant="success">
                <Check size={10} />
                Active
              </Badge>
              {connection.connectedAt && (
                <p className="text-xs text-muted-foreground">
                  Connected since {connection.connectedAt}
                </p>
              )}
            </div>
          </div>
        </div>

        <Separator />

        {/* Permissions granted */}
        <div className="flex flex-col gap-2 px-5 py-4">
          <p className="text-sm font-medium text-muted-foreground">
            Permissions granted
          </p>
          {PERMISSIONS.map((perm) => (
            <div key={perm} className="flex items-center gap-2">
              <Check className="h-3.5 w-3.5 shrink-0 text-success" />
              <span className="text-sm text-muted-foreground">{perm}</span>
            </div>
          ))}
        </div>

        {/* Calendar appointment link */}
        {calendarLink && (
          <>
            <Separator />
            <div className="flex flex-col gap-2.5 px-5 py-4">
              <div className="flex items-center gap-2">
                <Link2 className="h-4 w-4 text-muted-foreground" />
                <p className="text-sm font-semibold">
                  Calendar Appointment Link
                </p>
              </div>
              <p className="text-sm text-muted-foreground">
                Share with clients so they can self-book.
              </p>
              <div className="relative">
                <Input
                  id="calendar-link"
                  readOnly
                  value={calendarLink}
                  className="cursor-default select-all pr-10 text-muted-foreground"
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  onClick={onCopyLink}
                  className="absolute right-1 top-1/2 h-8 w-8 -translate-y-1/2"
                >
                  <Copy className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </>
        )}
      </div>
    );
  }

  // Not connected — direct user to Integrations instead of a second OAuth flow
  return (
    <div className="flex flex-col items-center gap-4 border border-border bg-card px-6 py-8 text-center">
      <div className="flex h-12 w-12 items-center justify-center bg-muted">
        <Mail className="h-6 w-6 text-muted-foreground" />
      </div>

      <div className="flex flex-col gap-1.5">
        <p className="text-base font-semibold">{label} not connected</p>
        <p className="max-w-xs text-sm text-muted-foreground">
          Connect your {label} account in Integrations to enable calendar
          booking and appointment confirmations.
        </p>
      </div>

      <div className="flex w-full max-w-xs flex-col gap-2 text-left">
        <p className="text-sm font-medium text-muted-foreground">
          Once connected, WealthX will be able to:
        </p>
        {PERMISSIONS.map((perm) => (
          <div key={perm} className="flex items-center gap-2">
            <Check className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
            <span className="text-sm text-muted-foreground">{perm}</span>
          </div>
        ))}
      </div>

      <Button onClick={onGoToIntegrations} className="gap-2">
        <ExternalLink className="h-4 w-4" />
        Go to Integrations
      </Button>
    </div>
  );
}
