'use client';

import {
  Anchor,
  Bell,
  Calendar,
  CheckCircle2,
  Clock,
  FileText,
  MoreHorizontal,
  Ship,
  User,
  XCircle,
} from 'lucide-react';
import { format } from 'date-fns';

import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ListCard, ListCardAvatar, ListCardMeta } from '@/components/shared/list-card';
import { cn } from '@/lib/utils';

interface Reminder {
  id: string;
  title: string;
  note: string | null;
  dueAt: string;
  priority: 'low' | 'medium' | 'high' | 'urgent';
  status: 'pending' | 'snoozed' | 'completed' | 'dismissed';
  assignedTo: string | null;
  createdBy: string;
  clientId: string | null;
  interestId: string | null;
  berthId: string | null;
  yachtId: string | null;
  autoGenerated: boolean;
  snoozedUntil: string | null;
  completedAt: string | null;
  createdAt: string;
  client?: { id: string; fullName: string } | null;
  interest?: { id: string; pipelineStage: string } | null;
  berth?: { id: string; mooringNumber: string } | null;
  yacht?: { id: string; name: string } | null;
}

const STATUS_CONFIG = {
  pending: { label: 'Pending', icon: Bell },
  snoozed: { label: 'Snoozed', icon: Clock },
  completed: { label: 'Completed', icon: CheckCircle2 },
  dismissed: { label: 'Dismissed', icon: XCircle },
} as const;

const STATUS_PILL: Record<string, string> = {
  pending: 'bg-amber-100 text-amber-700',
  snoozed: 'bg-slate-100 text-slate-700',
  completed: 'bg-emerald-100 text-emerald-700',
  dismissed: 'bg-emerald-100 text-emerald-700',
};

const PRIORITY_CONFIG = {
  urgent: { label: 'Urgent', className: 'bg-red-600 text-white' },
  high: { label: 'High', className: 'bg-orange-500 text-white' },
  medium: { label: 'Medium', className: 'bg-blue-500 text-white' },
  low: { label: 'Low', className: 'bg-gray-400 text-white' },
} as const;

function accentForReminder(status: string, isPastDue: boolean): string {
  if (isPastDue) return 'bg-rose-400';
  if (status === 'pending') return 'bg-amber-400';
  if (status === 'snoozed') return 'bg-slate-400';
  if (status === 'completed' || status === 'dismissed') return 'bg-emerald-400';
  return 'bg-slate-300';
}

interface ReminderCardProps {
  reminder: Reminder;
  portSlug: string;
  onComplete: (id: string) => void;
  onSnooze: (id: string) => void;
  onDismiss: (id: string) => void;
  onEdit: (reminder: Reminder) => void;
}

export function ReminderCard({
  reminder,
  portSlug: _portSlug,
  onComplete,
  onSnooze,
  onDismiss,
  onEdit,
}: ReminderCardProps) {
  const isPastDue =
    (reminder.status === 'pending' || reminder.status === 'snoozed') &&
    new Date(reminder.dueAt) < new Date();

  const accentClass = accentForReminder(reminder.status, isPastDue);
  const statusConfig = STATUS_CONFIG[reminder.status];
  const StatusIcon = statusConfig.icon;
  const statusPill = STATUS_PILL[reminder.status] ?? 'bg-slate-100 text-slate-700';
  const priorityConfig = PRIORITY_CONFIG[reminder.priority];

  const isResolved = reminder.status === 'completed' || reminder.status === 'dismissed';

  // Subtitle: related-entity context
  let subtitleIcon: React.ReactNode = null;
  let subtitleText: string | null = null;
  if (reminder.client) {
    subtitleIcon = <User className="h-3.5 w-3.5 shrink-0 text-muted-foreground/70" aria-hidden />;
    subtitleText = reminder.client.fullName;
  } else if (reminder.berth) {
    subtitleIcon = <Anchor className="h-3.5 w-3.5 shrink-0 text-muted-foreground/70" aria-hidden />;
    subtitleText = `Berth ${reminder.berth.mooringNumber}`;
  } else if (reminder.yacht) {
    subtitleIcon = <Ship className="h-3.5 w-3.5 shrink-0 text-muted-foreground/70" aria-hidden />;
    subtitleText = reminder.yacht.name;
  } else if (reminder.interest) {
    subtitleIcon = (
      <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground/70" aria-hidden />
    );
    subtitleText = `Interest (${reminder.interest.pipelineStage})`;
  }

  const hasActions = !isResolved;

  return (
    <ListCard
      href="#"
      ariaLabel={`Reminder: ${reminder.title}`}
      accentClassName={accentClass}
      actions={
        hasActions ? (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button
                variant="ghost"
                size="icon"
                className="h-9 w-9"
                onClick={(e) => e.stopPropagation()}
                aria-label={`Actions for reminder: ${reminder.title}`}
              >
                <MoreHorizontal className="h-4 w-4" aria-hidden />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem
                onClick={(e) => {
                  e.preventDefault();
                  onComplete(reminder.id);
                }}
              >
                <CheckCircle2 className="mr-2 h-3.5 w-3.5 text-green-600" aria-hidden />
                Complete
              </DropdownMenuItem>
              <DropdownMenuItem
                onClick={(e) => {
                  e.preventDefault();
                  onSnooze(reminder.id);
                }}
              >
                <Clock className="mr-2 h-3.5 w-3.5" aria-hidden />
                Snooze
              </DropdownMenuItem>
              <DropdownMenuItem
                onClick={(e) => {
                  e.preventDefault();
                  onEdit(reminder);
                }}
              >
                <Bell className="mr-2 h-3.5 w-3.5" aria-hidden />
                Edit
              </DropdownMenuItem>
              <DropdownMenuItem
                className="text-destructive"
                onClick={(e) => {
                  e.preventDefault();
                  onDismiss(reminder.id);
                }}
              >
                <XCircle className="mr-2 h-3.5 w-3.5" aria-hidden />
                Dismiss
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        ) : undefined
      }
    >
      <div className="flex items-start gap-3">
        <ListCardAvatar icon={<Bell className="h-5 w-5" aria-hidden />} />
        <div className="min-w-0 flex-1">
          {/* Title row + spacer for actions button */}
          <div className="flex items-start justify-between gap-2">
            <h3 className="truncate text-base font-semibold tracking-tight text-foreground">
              {reminder.title}
            </h3>
            {hasActions ? <span aria-hidden className="block h-9 w-9 shrink-0" /> : null}
          </div>

          {/* Related entity subtitle */}
          {subtitleText ? (
            <p className="mt-0.5 inline-flex items-center gap-1 truncate text-sm text-muted-foreground">
              {subtitleIcon}
              <span className="truncate">{subtitleText}</span>
            </p>
          ) : null}

          {/* Due date meta line */}
          <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
            <ListCardMeta
              icon={
                <Calendar
                  className={cn(
                    'h-3 w-3',
                    isPastDue ? 'text-rose-500' : 'text-muted-foreground/80',
                  )}
                />
              }
            >
              <span className={isPastDue ? 'font-medium text-rose-600' : ''}>
                Due {format(new Date(reminder.dueAt), 'MMM d, yyyy')}
              </span>
            </ListCardMeta>
          </div>

          {/* Pills row: status + priority + past-due flag */}
          <div className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1">
            {/* Status pill */}
            <span
              className={cn(
                'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium',
                statusPill,
              )}
            >
              <StatusIcon className="h-3 w-3" aria-hidden />
              {statusConfig.label}
            </span>

            {/* Priority pill */}
            <span
              className={cn(
                'inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium',
                priorityConfig.className,
              )}
            >
              {priorityConfig.label}
            </span>

            {/* Past-due flag */}
            {isPastDue ? (
              <span className="inline-flex items-center rounded-full bg-rose-100 px-2 py-0.5 text-xs font-medium text-rose-700">
                Past due
              </span>
            ) : null}
          </div>
        </div>
      </div>
    </ListCard>
  );
}
