import React from "react";
import { Badge } from "./badge";
import { Button } from "./button";
import { Avatar, AvatarFallback, AvatarImage } from "./avatar";
import { Separator } from "./separator";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "./dropdown-menu";
import {
  Calendar,
  CalendarCheck,
  ChevronRight,
  Mail,
  MoreVertical,
  Phone,
  Plus,
} from "lucide-react";
import type { AppointmentStatus } from "./appointment-time-slot-picker";

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

/** A single item in the ⋮ overflow DropdownMenu */
export interface AdvisorCardMenuItem {
  /** Display label */
  label: string;
  /** Called when the item is clicked */
  onClick: () => void;
  /** Visual variant — use "destructive" for delete/remove actions */
  variant?: "default" | "destructive";
  /** Disables the item without removing it */
  disabled?: boolean;
}

/** Appointment data shown in the strip inside the advisor card */
export interface AdvisorAppointmentStrip {
  status: AppointmentStatus;
  /** Human-readable appointment type — e.g. "Financial Review" */
  appointmentType?: string;
  /** Display date string — e.g. "Wed, 23 Apr 2026" */
  date: string;
  /** Display start time — e.g. "2:00 PM" */
  timeStart: string;
  /** Display end time — e.g. "2:30 PM" */
  timeEnd: string;
}

export interface AdvisorCardProps {
  /** Advisor full name */
  name: string;
  /** Job title / role label */
  role: string;
  /** Phone number string */
  phone: string;
  /** Email address */
  email: string;
  /** Broker company name — shown as text fallback when no logo is provided */
  companyName?: string;
  /** URL of the broker company logo — renders as avatar image */
  companyLogoUrl?: string;
  /** Explicit initials for the avatar fallback; derived from companyName if omitted */
  avatarInitials?: string;
  /** Whether this is the client's primary assigned advisor */
  isPrimary?: boolean;
  /**
   * Upcoming appointments shown as stacked strips.
   * - `undefined` — strip section hidden
   * - `null` or `[]` — empty state: "No upcoming appointments"
   * - array of items — one coloured strip per appointment
   */
  appointments?: AdvisorAppointmentStrip[] | null;
  /** Called when "Refer [name] to Others" is clicked */
  onRefer?: () => void;
  /**
   * Items to render in the ⋮ overflow DropdownMenu.
   * When provided, the button opens an inline dropdown — `onMoreOptions` is ignored.
   */
  menuItems?: AdvisorCardMenuItem[];
  /** @deprecated Pass `menuItems` for an inline DropdownMenu instead */
  onMoreOptions?: () => void;
  /** Called when "Book Appointment" is clicked */
  onBookAppointment?: () => void;
  /** Called when "View →" in an appointment strip is clicked; receives the appointment index */
  onViewAppointment?: (index: number) => void;
}

export interface AdvisorInviteCardProps {
  /** Called when the "Add Advisor" CTA is clicked */
  onInvite?: () => void;
}

// ---------------------------------------------------------------------------
// Status config
// ---------------------------------------------------------------------------

const STATUS_VARIANT: Record<
  AppointmentStatus,
  "warning" | "success" | "destructive" | "info"
> = {
  pending: "warning",
  confirmed: "success",
  cancelled: "destructive",
  rescheduled: "info",
};

const STATUS_LABEL: Record<AppointmentStatus, string> = {
  pending: "Pending",
  confirmed: "Confirmed",
  cancelled: "Cancelled",
  rescheduled: "Rescheduled",
};

const STRIP_BG: Record<AppointmentStatus, string> = {
  pending: "bg-warning/5",
  confirmed: "bg-success/5",
  cancelled: "bg-destructive/5",
  rescheduled: "bg-info/5",
};

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

export function AdvisorCard({
  name,
  role,
  phone,
  email,
  companyName,
  companyLogoUrl,
  avatarInitials,
  isPrimary = false,
  appointments,
  onRefer,
  menuItems,
  onMoreOptions,
  onBookAppointment,
  onViewAppointment,
}: AdvisorCardProps) {
  const hasAppointments = appointments !== undefined;
  const appointmentList =
    appointments === null ||
    (Array.isArray(appointments) && appointments.length === 0)
      ? null
      : appointments;

  return (
    <div className="flex flex-col border border-border bg-card">
      {/* ── Advisor info ── */}
      <div className="flex items-start gap-4 p-4">
        <Avatar className="h-10 w-10 shrink-0">
          {companyLogoUrl && (
            <AvatarImage src={companyLogoUrl} alt={`${name} company logo`} />
          )}
          <AvatarFallback className="text-caption">
            {avatarInitials ??
              (companyName
                ? companyName
                    .split(" ")
                    .map((w) => w[0])
                    .join("")
                    .slice(0, 2)
                    .toUpperCase()
                : name.slice(0, 2).toUpperCase())}
          </AvatarFallback>
        </Avatar>

        <div className="flex min-w-0 flex-1 flex-col gap-0.5">
          <div className="flex flex-wrap items-center gap-2">
            <p className="text-label-large leading-tight">{name}</p>
            {isPrimary && <Badge variant="success">Primary</Badge>}
          </div>
          <p className="text-body-small text-muted-foreground">{role}</p>
          <div className="mt-2 flex flex-col gap-1">
            <div className="flex items-center gap-1.5 text-body-small text-muted-foreground">
              <Phone className="h-4 w-4 shrink-0" />
              <span>{phone}</span>
            </div>
            <div className="flex items-center gap-1.5 text-body-small text-muted-foreground">
              <Mail className="h-4 w-4 shrink-0" />
              <span>{email}</span>
            </div>
          </div>
        </div>

        {/* Overflow menu */}
        <div className="flex shrink-0 items-center gap-1.5">
          {menuItems && menuItems.length > 0 ? (
            <DropdownMenu>
              <DropdownMenuTrigger
                render={
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-7 w-7"
                    aria-label="More options"
                  />
                }
              >
                <MoreVertical className="h-4 w-4" />
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                {menuItems.map((item, i) => (
                  <DropdownMenuItem
                    key={i}
                    variant={item.variant}
                    disabled={item.disabled}
                    onClick={item.onClick}
                  >
                    {item.label}
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>
          ) : (
            <Button
              variant="ghost"
              size="icon"
              className="h-7 w-7"
              onClick={onMoreOptions}
              aria-label="More options"
            >
              <MoreVertical className="h-4 w-4" />
            </Button>
          )}
        </div>
      </div>

      {/* ── Appointment strips ── */}
      {hasAppointments && (
        <>
          <Separator />
          {appointmentList ? (
            appointmentList.map((appt, i) => (
              <React.Fragment key={i}>
                {i > 0 && <Separator />}
                <div
                  className={`flex items-center gap-3 px-4 py-3 ${STRIP_BG[appt.status]}`}
                >
                  <CalendarCheck className="h-4 w-4 shrink-0 text-muted-foreground" />
                  <div className="flex min-w-0 flex-1 flex-col gap-0.5">
                    <div className="flex min-w-0 items-center gap-2">
                      <Badge variant={STATUS_VARIANT[appt.status]}>
                        {STATUS_LABEL[appt.status]}
                      </Badge>
                      {appt.appointmentType && (
                        <span className="min-w-0 truncate text-h6">
                          {appt.appointmentType}
                        </span>
                      )}
                    </div>
                    <p className="text-body-small text-muted-foreground">
                      {appt.date} · {appt.timeStart}–{appt.timeEnd}
                    </p>
                  </div>
                  {onViewAppointment && (
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-7 shrink-0 gap-1 px-2 text-xs"
                      onClick={() => onViewAppointment(i)}
                    >
                      View
                      <ChevronRight className="h-3 w-3" />
                    </Button>
                  )}
                </div>
              </React.Fragment>
            ))
          ) : (
            /* Empty state */
            <div className="flex items-center gap-3 px-4 py-3">
              <Calendar className="h-4 w-4 shrink-0 text-muted-foreground" />
              <p className="flex-1 text-caption text-muted-foreground">
                No upcoming appointments
              </p>
            </div>
          )}
        </>
      )}

      {/* ── Footer actions ── */}
      <Separator />
      <div className="flex flex-col gap-2 px-4 py-3">
        {onBookAppointment && (
          <Button
            variant="outline-primary"
            size="sm"
            className="w-full"
            onClick={onBookAppointment}
          >
            Book Appointment
          </Button>
        )}
        {onRefer && (
          <Button
            variant="default"
            size="sm"
            className="w-full"
            onClick={onRefer}
          >
            Refer {name} to Others
          </Button>
        )}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// AdvisorInviteCard
// ---------------------------------------------------------------------------

export function AdvisorInviteCard({ onInvite }: AdvisorInviteCardProps) {
  return (
    <Button
      variant="ghost"
      onClick={onInvite}
      className="flex h-auto w-full flex-col items-center justify-center gap-3 border border-dashed border-border bg-card p-8 text-center transition-colors hover:bg-muted/40"
    >
      <div className="flex h-10 w-10 items-center justify-center border border-dashed border-muted-foreground/40">
        <Plus className="h-5 w-5 text-muted-foreground" />
      </div>
      <div className="flex flex-col gap-1">
        <p className="text-label-large">Add Another Adviser</p>
        <p className="text-caption text-muted-foreground">
          Connect more advisers to your account
        </p>
      </div>
    </Button>
  );
}
