"use client"

/**
 * MeetingsList — table-style meeting list with status badges, join links,
 * and an optional delete action.
 *
 * Distinct from UpcomingMeetings (sidebar card-stack); this is the
 * full-width table-row layout used by /calendar's "All Meetings" section
 * and /fundraises/[id]/outreach's MeetingsTab (Upcoming + Past lists).
 *
 * Pure presentational. The consumer owns sort, filter, fetch, and delete
 * confirmation.
 *
 * lifecycle:calendar-ui (raise-simpli-9cp)
 */

import * as React from "react"
import { CalendarDays, ExternalLink, Plus, Trash2 } from "lucide-react"
import { Button } from "../ui/button"
import { cn } from "../../utils"

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

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

export interface MeetingsListProps<T extends MeetingsListItem = MeetingsListItem> {
  meetings: T[]
  /** Whether the list is still loading. */
  loading?: boolean
  /** Number of skeleton rows to show while loading. Defaults to 4. */
  loadingRowCount?: number
  /** If set, each row gets a delete (trash) button that calls this with the id. */
  onDelete?: (id: string | number) => void
  /** If set, the whole row becomes clickable. */
  onRowClick?: (meeting: T) => void
  /** If set, the empty state shows a "Schedule First Meeting" CTA wired to this. */
  onSchedule?: () => void
  /** Empty-state copy. Defaults to "No meetings scheduled yet." */
  emptyMessage?: string
  /** className passed to the wrapping div. */
  className?: string
}

const STATUS_BADGE: Record<MeetingsListStatus, { 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",
    year: "numeric",
  })
}

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

/**
 * @example
 * <MeetingsList
 *   meetings={meetings}
 *   loading={loading}
 *   onDelete={id => deleteMeeting(id)}
 *   onSchedule={() => setShowSchedule(true)}
 * />
 */
export function MeetingsList<T extends MeetingsListItem = MeetingsListItem>({
  meetings,
  loading = false,
  loadingRowCount = 4,
  onDelete,
  onRowClick,
  onSchedule,
  emptyMessage = "No meetings scheduled yet.",
  className,
}: MeetingsListProps<T>) {
  if (loading) {
    return (
      <div className={cn("p-4 space-y-2", className)}>
        {Array.from({ length: loadingRowCount }).map((_, i) => (
          <div key={i} className="h-12 bg-muted animate-pulse rounded" />
        ))}
      </div>
    )
  }

  if (meetings.length === 0) {
    return (
      <div className={cn("text-center py-12 text-muted-foreground", className)}>
        <CalendarDays className="h-10 w-10 mx-auto mb-3 opacity-40" />
        <p>{emptyMessage}</p>
        {onSchedule && (
          <Button className="mt-3" onClick={onSchedule}>
            <Plus className="mr-2 h-4 w-4" />
            Schedule First Meeting
          </Button>
        )}
      </div>
    )
  }

  return (
    <div className={cn("divide-y", className)}>
      {meetings.map(m => {
        const badge = STATUS_BADGE[m.status]
        const interactive = !!onRowClick
        return (
          <div
            key={m.id}
            role={interactive ? "button" : undefined}
            tabIndex={interactive ? 0 : undefined}
            onClick={interactive ? () => onRowClick(m) : undefined}
            onKeyDown={
              interactive
                ? e => {
                    if (e.key === "Enter" || e.key === " ") {
                      e.preventDefault()
                      onRowClick(m)
                    }
                  }
                : undefined
            }
            className={cn(
              "flex items-center justify-between px-4 py-3 transition-colors",
              interactive && "hover:bg-muted/50 cursor-pointer",
              !interactive && "hover:bg-muted/50",
            )}
          >
            <div className="flex items-center gap-4 min-w-0">
              <div className="min-w-0">
                <p className="font-medium text-sm truncate">{m.title}</p>
                {(m.investor_name || m.investor_email) && (
                  <p className="text-xs text-muted-foreground truncate">
                    {m.investor_name || m.investor_email}
                  </p>
                )}
              </div>
            </div>

            <div className="flex items-center gap-4 shrink-0 ml-4">
              <div className="text-right text-xs text-muted-foreground hidden sm:block">
                <p>{formatDate(m.scheduled_at)}</p>
                <p>
                  {formatTime(m.scheduled_at)}
                  {m.duration_minutes ? ` · ${m.duration_minutes}min` : ""}
                </p>
              </div>

              <span className={cn("text-xs px-2 py-0.5 rounded font-medium", badge.className)}>
                {badge.label}
              </span>

              {m.meeting_link && (
                <a
                  href={m.meeting_link}
                  target="_blank"
                  rel="noreferrer"
                  onClick={e => e.stopPropagation()}
                  className="text-primary"
                  title="Join meeting"
                >
                  <ExternalLink className="h-4 w-4" />
                </a>
              )}

              {onDelete && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={e => {
                    e.stopPropagation()
                    onDelete(m.id)
                  }}
                  className="h-7 w-7 p-0 text-muted-foreground hover:text-red-600"
                  aria-label="Delete meeting"
                >
                  <Trash2 className="h-3.5 w-3.5" />
                </Button>
              )}
            </div>
          </div>
        )
      })}
    </div>
  )
}
