"use client"

/**
 * UpcomingMeetings — sidebar/widget listing the next N meetings with status,
 * date, time, and an optional join-link.
 *
 * Pure presentational. The consumer owns the data fetch + filtering — pass
 * the already-filtered, already-sorted meetings via the `meetings` prop. This
 * keeps the component decoupled from any specific API client or data shape
 * beyond the small interface declared below.
 *
 * lifecycle:calendar-ui (raise-simpli-azc)
 */

import * as React from "react"
import { CalendarDays, Clock, ExternalLink, Plus } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card"
import { Button } from "../ui/button"
import { cn } from "../../utils"

export type UpcomingMeetingStatus = "pending" | "confirmed" | "cancelled" | "completed"

export interface UpcomingMeeting {
  id: string | number
  title: string
  /** ISO 8601 timestamp string */
  scheduled_at: string
  status: UpcomingMeetingStatus
  investor_name?: string
  investor_email?: string
  meeting_link?: string
}

export interface UpcomingMeetingsProps<T extends UpcomingMeeting = UpcomingMeeting> {
  meetings: T[]
  /** Whether the list is still loading. Renders skeletons. */
  loading?: boolean
  /** Optional click handler when a meeting row is clicked (whole row). */
  onMeetingClick?: (meeting: T) => void
  /** Optional URL for the "View all" header link. Hidden if absent. */
  viewAllHref?: string
  /** Optional click handler for the "View all" header link. Used instead of href if provided. */
  onViewAll?: () => void
  /** Optional click handler for the empty-state "Schedule one" CTA. Hidden if absent. */
  onSchedule?: () => void
  /** Custom class name for the outer Card. */
  className?: string
  /** Title shown in the card header. Defaults to "Upcoming Meetings". */
  title?: string
  /** Number of skeleton rows to show while loading. Defaults to 3. */
  loadingRowCount?: number
}

const STATUS_BADGE: Record<UpcomingMeetingStatus, { label: string; className: string }> = {
  pending: { label: "Pending", className: "bg-yellow-100 text-yellow-800" },
  confirmed: { label: "Confirmed", className: "bg-green-100 text-green-800" },
  cancelled: { label: "Cancelled", className: "bg-red-100 text-red-800" },
  completed: { label: "Completed", className: "bg-gray-100 text-gray-800" },
}

function formatDate(isoStr: string): string {
  return new Date(isoStr).toLocaleDateString("en-US", {
    weekday: "short",
    month: "short",
    day: "numeric",
  })
}

function formatTime(isoStr: string): string {
  return new Date(isoStr).toLocaleTimeString("en-US", {
    hour: "2-digit",
    minute: "2-digit",
  })
}

/**
 * @example
 * <UpcomingMeetings
 *   meetings={upcoming}
 *   loading={isLoading}
 *   viewAllHref="/calendar"
 *   onSchedule={() => setShowSchedule(true)}
 * />
 */
export function UpcomingMeetings<T extends UpcomingMeeting = UpcomingMeeting>({
  meetings,
  loading = false,
  onMeetingClick,
  viewAllHref,
  onViewAll,
  onSchedule,
  className,
  title = "Upcoming Meetings",
  loadingRowCount = 3,
}: UpcomingMeetingsProps<T>) {
  return (
    <Card className={className}>
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="text-sm font-semibold flex items-center gap-2">
            <CalendarDays className="h-4 w-4" />
            {title}
          </CardTitle>
          {(viewAllHref || onViewAll) && (
            <Button
              variant="ghost"
              size="sm"
              className="h-7 text-xs"
              asChild={!!viewAllHref && !onViewAll}
              onClick={onViewAll}
            >
              {viewAllHref && !onViewAll ? <a href={viewAllHref}>View all</a> : <span>View all</span>}
            </Button>
          )}
        </div>
      </CardHeader>

      <CardContent className="pt-0">
        {loading ? (
          <div className="space-y-2">
            {Array.from({ length: loadingRowCount }).map((_, i) => (
              <div key={i} className="h-14 bg-muted animate-pulse rounded-md" />
            ))}
          </div>
        ) : meetings.length === 0 ? (
          <div className="text-center py-6 text-muted-foreground">
            <CalendarDays className="h-8 w-8 mx-auto mb-2 opacity-40" />
            <p className="text-xs">No upcoming meetings</p>
            {onSchedule && (
              <Button variant="outline" size="sm" className="mt-3 h-7 text-xs" onClick={onSchedule}>
                <Plus className="mr-1 h-3 w-3" />
                Schedule one
              </Button>
            )}
          </div>
        ) : (
          <div className="space-y-2">
            {meetings.map(m => {
              const badge = STATUS_BADGE[m.status]
              const interactive = !!onMeetingClick
              return (
                <div
                  key={m.id}
                  role={interactive ? "button" : undefined}
                  tabIndex={interactive ? 0 : undefined}
                  onClick={interactive ? () => onMeetingClick(m) : undefined}
                  onKeyDown={
                    interactive
                      ? e => {
                          if (e.key === "Enter" || e.key === " ") {
                            e.preventDefault()
                            onMeetingClick(m)
                          }
                        }
                      : undefined
                  }
                  className={cn(
                    "border rounded-lg p-2.5 space-y-1 transition-colors",
                    interactive && "hover:bg-muted/40 cursor-pointer",
                  )}
                >
                  <div className="flex items-start justify-between gap-2">
                    <p className="font-medium text-xs leading-tight line-clamp-1">{m.title}</p>
                    <span
                      className={cn(
                        "text-[10px] px-1.5 py-0.5 rounded font-medium whitespace-nowrap shrink-0",
                        badge.className,
                      )}
                    >
                      {badge.label}
                    </span>
                  </div>

                  {(m.investor_name || m.investor_email) && (
                    <p className="text-[11px] text-muted-foreground truncate">
                      {m.investor_name || m.investor_email}
                    </p>
                  )}

                  <div className="flex items-center gap-3 text-[11px] text-muted-foreground">
                    <span className="flex items-center gap-1">
                      <CalendarDays className="h-3 w-3" />
                      {formatDate(m.scheduled_at)}
                    </span>
                    <span className="flex items-center gap-1">
                      <Clock className="h-3 w-3" />
                      {formatTime(m.scheduled_at)}
                    </span>
                  </div>

                  {m.meeting_link && (
                    <a
                      href={m.meeting_link}
                      target="_blank"
                      rel="noreferrer"
                      onClick={e => e.stopPropagation()}
                      className="flex items-center gap-1 text-[11px] text-primary hover:underline"
                    >
                      <ExternalLink className="h-3 w-3" />
                      Join
                    </a>
                  )}
                </div>
              )
            })}
          </div>
        )}
      </CardContent>
    </Card>
  )
}
