'use client';

import type { FC } from 'react';
import { Icons } from '@/components/icons';
import { cn } from '@/lib/utils';

export type NotificationStatus = 'unread' | 'read' | 'archived';
export type ActionType = 'redirect' | 'api_call' | 'workflow' | 'modal';
export type ActionStyle = 'primary' | 'danger' | 'default';

export interface NotificationAction {
  id: string;
  label: string;
  type: ActionType;
  style?: ActionStyle;
  executed?: boolean;
}

export interface NotificationCardProps {
  id: string | number;
  title: string;
  body: string;
  status?: NotificationStatus;
  createdAt?: string | Date;
  actions?: NotificationAction[];
  onMarkAsRead?: (id: number) => void;
  onAction?: (notificationId: number, actionId: string, actionType: ActionType) => void;
  loadingActionId?: string;
  className?: string;
}

const formatDate = (date: string | Date): string => {
  const targetDate = new Date(date);
  const now = new Date();
  const diffMs = now.getTime() - targetDate.getTime();
  const diffMins = Math.floor(diffMs / (1000 * 60));
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

  if (diffMins < 1) return 'เมื่อสักครู่';
  if (diffMins < 60) return `${diffMins} นาทีที่แล้ว`;
  if (diffHours < 24) return `${diffHours} ชั่วโมงที่แล้ว`;
  if (diffDays < 7) return `${diffDays} วันที่แล้ว`;

  return targetDate.toLocaleDateString('th-TH', {
    day: 'numeric',
    month: 'short'
  });
};

const getActionIcon = (actionType: ActionType) => {
  const iconProps = { size: 12, strokeWidth: 2.5 };

  switch (actionType) {
    case 'redirect':
      return <Icons.externalLink {...iconProps} />;
    case 'api_call':
      return <Icons.check {...iconProps} />;
    case 'workflow':
      return <Icons.clock {...iconProps} />;
    case 'modal':
      return <Icons.alertCircle {...iconProps} />;
    default:
      return null;
  }
};

export const NotificationCard: FC<NotificationCardProps> = ({
  id,
  title,
  body,
  status = 'unread',
  createdAt,
  actions = [],
  onMarkAsRead,
  onAction,
  loadingActionId,
  className
}) => {
  const numericId = Number(id);
  const isUnread = status === 'unread';

  return (
    <div
      className={cn(
        'group relative w-full rounded-xl border transition-all',
        isUnread ? 'bg-muted/70 border-border' : 'bg-muted/30 border-border/60',
        className
      )}
    >
      <div className='px-4 py-3.5'>
        <div className='flex items-start justify-between gap-3'>
          <div className='min-w-0 flex-1 space-y-1'>
            <div className='flex items-center gap-2'>
              <h3
                className={cn(
                  'text-sm leading-tight font-semibold',
                  isUnread ? 'text-foreground' : 'text-foreground/80'
                )}
              >
                {title}
              </h3>
              {isUnread && <div className='h-2 w-2 flex-shrink-0 rounded-full bg-sky-500' />}
            </div>

            <p
              className={cn(
                'text-sm leading-relaxed',
                isUnread ? 'text-muted-foreground' : 'text-muted-foreground/80'
              )}
            >
              {body}
            </p>
          </div>

          {isUnread && onMarkAsRead && Number.isFinite(numericId) && (
            <button
              type='button'
              onClick={() => onMarkAsRead(numericId)}
              className={cn(
                'rounded-lg p-1.5 transition-colors',
                'text-muted-foreground hover:bg-accent hover:text-foreground'
              )}
              aria-label='อ่านแล้ว'
            >
              <Icons.check size={16} />
            </button>
          )}
        </div>

        <div className='mt-3 flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between'>
          {actions.length > 0 ? (
            <div className={cn('flex flex-wrap items-center gap-2', !isUnread && 'opacity-80')}>
              {actions.map((action) => {
                const isLoading = loadingActionId === action.id;
                const isExecuted = action.executed || false;
                const showLoading = isLoading && action.type !== 'modal';

                return (
                  <button
                    key={action.id}
                    type='button'
                    disabled={isLoading || isExecuted || !Number.isFinite(numericId)}
                    onClick={() => onAction?.(numericId, action.id, action.type)}
                    className={cn(
                      'flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs transition',
                      action.style === 'primary'
                        ? 'bg-primary/10 text-primary hover:bg-primary/20'
                        : action.style === 'danger'
                          ? 'bg-destructive/10 text-destructive hover:bg-destructive/20'
                          : 'bg-accent text-muted-foreground hover:bg-accent hover:text-foreground',
                      showLoading && 'opacity-50',
                      isExecuted && 'cursor-not-allowed opacity-60'
                    )}
                  >
                    {showLoading ? (
                      <Icons.spinner size={12} className='animate-spin' />
                    ) : (
                      <>
                        <span>{action.label}</span>
                        {isExecuted ? (
                          <Icons.check size={12} strokeWidth={2.5} />
                        ) : (
                          getActionIcon(action.type)
                        )}
                      </>
                    )}
                  </button>
                );
              })}
            </div>
          ) : null}

          {createdAt && (
            <span className='text-muted-foreground inline-block text-[11px]'>
              {formatDate(createdAt)}
            </span>
          )}
        </div>
      </div>
    </div>
  );
};
