import React, { useMemo } from 'react';
import { ArrowDown, ArrowUp, Copy, GripVertical, History } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { scheduleLabel } from '@/lib/billingSchedule';
import type { Bill } from '@/types';
import type { DragProps, MoveControls } from '@/components/tracker/MobileTrackerRow';

function hasHistoricalVisibility(bill: Bill): boolean {
  const visibility = bill.history_visibility;
  return !!bill.has_history_ranges || (!!visibility && visibility !== 'default');
}

interface MobileBillRowProps {
  bill: Bill;
  onEdit?: (id: number) => void;
  onToggle?: (bill: Bill) => void;
  onDelete?: (bill: Bill) => void;
  onHistory?: (bill: Bill) => void;
  onDuplicate?: (bill: Bill) => void;
  moveControls?: MoveControls;
  dragProps?: DragProps;
}

export const MobileBillRow = React.memo(function MobileBillRow({ bill, onEdit, onToggle, onDelete, onHistory, onDuplicate, moveControls, dragProps }: MobileBillRowProps) {
  const hasHistory = useMemo(() => hasHistoricalVisibility(bill), [bill]);

  const statusClass = useMemo(() => {
    return cn(
      'rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide',
      bill.active
        ? 'bg-emerald-500/20 text-emerald-300'
        : 'bg-muted text-muted-foreground',
    );
  }, [bill.active]);

  const toggleBtnClass = useMemo(() => {
    return cn(
      'h-8 px-2.5 text-xs',
      bill.active
        ? 'text-muted-foreground hover:text-destructive'
        : 'text-emerald-500 hover:text-emerald-400',
    );
  }, [bill.active]);

  return (
    <div
      draggable={dragProps?.draggable}
      onDragStart={dragProps?.onDragStart as React.ComponentProps<'div'>['onDragStart']}
      onDragEnter={dragProps?.onDragEnter as React.ComponentProps<'div'>['onDragEnter']}
      onDragOver={dragProps?.onDragOver as React.ComponentProps<'div'>['onDragOver']}
      onDragEnd={dragProps?.onDragEnd as React.ComponentProps<'div'>['onDragEnd']}
      onDrop={dragProps?.onDrop as React.ComponentProps<'div'>['onDrop']}
      className={cn(
        'group rounded-xl border border-border/80 bg-card/90 p-3 shadow-sm shadow-black/10',
        dragProps?.isDragging && 'opacity-45',
        dragProps?.isDropTarget && 'ring-2 ring-primary/40',
      )}
    >
      <div className="flex min-w-0 items-start justify-between gap-3">
        <div className="flex shrink-0 items-center gap-0.5">
          <GripVertical
            className={cn(
              'h-4 w-4 text-muted-foreground/55',
              moveControls?.enabled && 'cursor-grab',
              !moveControls?.enabled && 'opacity-30',
            )}
            aria-hidden="true"
          />
          <div className="flex flex-col">
            <button
              type="button"
              onClick={moveControls?.onMoveUp}
              disabled={!moveControls?.enabled || !moveControls?.canMoveUp || moveControls?.moving}
              className="rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-25"
              title="Move bill up"
              aria-label={`Move ${bill.name} up`}
            >
              <ArrowUp className="h-3 w-3" />
            </button>
            <button
              type="button"
              onClick={moveControls?.onMoveDown}
              disabled={!moveControls?.enabled || !moveControls?.canMoveDown || moveControls?.moving}
              className="rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-25"
              title="Move bill down"
              aria-label={`Move ${bill.name} down`}
            >
              <ArrowDown className="h-3 w-3" />
            </button>
          </div>
        </div>

        <div className="min-w-0 flex-1">
          <div className="flex min-w-0 items-center gap-2">
            <button
              type="button"
              className="min-w-0 truncate text-left text-sm font-semibold leading-tight text-foreground underline-offset-4 transition-colors hover:text-primary hover:underline focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 rounded-sm"
              onClick={() => onEdit?.(bill.id)}
              title={`Edit ${bill.name}`}
            >
              {bill.name}
            </button>
            {hasHistory && (
              <span
                className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full border border-sky-500/25 bg-sky-500/10 text-sky-500"
                title="Historical visibility configured"
                aria-label="Historical visibility configured"
              >
                <History className="h-3 w-3" />
              </span>
            )}
          </div>

          <div className="mt-1 flex flex-wrap items-center gap-1.5">
            <span className={statusClass}>
              {bill.active ? 'Active' : 'Inactive'}
            </span>
            {bill.autopay_enabled ? (
              <span className="rounded bg-emerald-500/20 px-1.5 py-0.5 text-[10px] font-semibold text-emerald-300">AP</span>
            ) : null}
            {bill.has_2fa ? (
              <span className="rounded bg-violet-500/20 px-1.5 py-0.5 text-[10px] font-semibold text-violet-300">2FA</span>
            ) : null}
            {(bill.has_merchant_rule || bill.has_linked_transactions) ? (
              <span className="rounded border border-emerald-500/25 bg-emerald-500/10 px-1.5 py-0.5 text-[10px] font-semibold text-emerald-600 dark:text-emerald-400" title="Linked to bank transactions">L</span>
            ) : null}
            {bill.is_subscription ? (
              <span className="rounded border border-indigo-500/25 bg-indigo-500/10 px-1.5 py-0.5 text-[10px] font-semibold text-indigo-600 dark:text-indigo-300">S</span>
            ) : null}
          </div>
        </div>

        <span className="tracker-number shrink-0 text-sm font-bold text-foreground">
          ${Number(bill.expected_amount).toFixed(2)}
        </span>
      </div>

      <div className="mt-3 grid grid-cols-3 gap-2 text-xs font-medium text-muted-foreground">
        <div>
          <p className="uppercase tracking-normal text-muted-foreground">Due</p>
          <p className="mt-0.5 text-sm text-foreground">Day {bill.due_day}</p>
        </div>
        <div className="min-w-0">
          <p className="uppercase tracking-normal text-muted-foreground">Category</p>
          <p className="mt-0.5 truncate text-sm text-foreground">{bill.category_name || '—'}</p>
        </div>
        <div>
          <p className="uppercase tracking-normal text-muted-foreground">Cycle</p>
          <p className="mt-0.5 text-sm text-foreground">{scheduleLabel(bill)}</p>
        </div>
      </div>

      <div className="mt-3 flex flex-wrap items-center justify-end gap-1.5">
        <Button
          variant="ghost"
          size="sm"
          className="h-8 gap-1.5 px-2.5 text-xs text-muted-foreground hover:text-primary"
          onClick={() => onDuplicate?.(bill)}
        >
          <Copy className="h-3.5 w-3.5" />
          Duplicate
        </Button>
        <Button
          variant="ghost"
          size="sm"
          className={toggleBtnClass}
          onClick={() => onToggle?.(bill)}
        >
          {bill.active ? 'Deactivate' : 'Activate'}
        </Button>
        {!bill.active && (
          <Button
            variant="ghost"
            size="sm"
            className="h-8 px-2.5 text-xs text-sky-500 hover:text-sky-400 hover:bg-sky-500/10"
            onClick={() => onHistory?.(bill)}
          >
            History
          </Button>
        )}
        <Button
          variant="ghost"
          size="sm"
          className="h-8 px-2.5 text-xs text-destructive hover:text-destructive hover:bg-destructive/10"
          onClick={() => onDelete?.(bill)}
        >
          Delete
        </Button>
      </div>
    </div>
  );
});

MobileBillRow.displayName = 'MobileBillRow';
