import { useState } from 'react';
import { BellOff, CalendarClock, ChevronDown, ChevronUp, Clock3, CreditCard, EyeOff, SkipForward } from 'lucide-react';
import { toast } from 'sonner';
import { api } from '@/api';
import { fmt, localDateString } from '@/lib/utils';
import { asDollars } from '@/lib/money';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible';
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
} from '@/components/ui/dropdown-menu';
import type { TrackerRow } from '@/types';

function snoozeUntil(days: number): string {
  const d = new Date();
  d.setDate(d.getDate() + days);
  return localDateString(d);
}

function daysOverdueLabel(dueDate: string | null | undefined): string {
  if (!dueDate) return 'overdue';
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const due = new Date(`${dueDate}T00:00:00`);
  const days = Math.floor((today.getTime() - due.getTime()) / 86_400_000);
  if (days <= 0) return 'due today';
  return `${days} ${days === 1 ? 'day' : 'days'} overdue`;
}

interface OverdueRowProps {
  row: TrackerRow;
  year: number;
  month: number;
  onPayNow: (row: TrackerRow) => void;
  onRefresh: () => void;
}

function OverdueRow({ row, year, month, onPayNow, onRefresh }: OverdueRowProps) {
  const [loading, setLoading] = useState(false);
  const threshold = row.actual_amount ?? row.expected_amount;
  const remaining = Math.max(0, threshold - (row.total_paid ?? 0));

  async function handleSkip() {
    setLoading(true);
    try {
      await api.saveBillMonthlyState(row.id, {
        year,
        month,
        is_skipped: true,
        actual_amount: row.actual_amount,
        notes: row.monthly_notes,
      });
      onRefresh();
    } catch {
      toast.error('Failed to skip bill');
    } finally {
      setLoading(false);
    }
  }

  async function handleSnooze(days: number) {
    setLoading(true);
    try {
      await api.snoozeOverdue(row.id, {
        year,
        month,
        snoozed_until: snoozeUntil(days),
        actual_amount: row.actual_amount,
        notes: row.monthly_notes,
        is_skipped: false,
      });
      toast.success(`Snoozed for ${days} ${days === 1 ? 'day' : 'days'}`);
      onRefresh();
    } catch {
      toast.error('Failed to snooze bill');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex flex-wrap items-center gap-x-3 gap-y-2 rounded-lg px-2 py-2.5 transition-colors hover:bg-card/55 sm:flex-nowrap">
      {/* Bill info */}
      <div className="flex min-w-0 flex-1 flex-col gap-0.5">
        <div className="flex flex-wrap items-center gap-1.5">
          <span className="truncate text-sm font-medium text-foreground">{row.name}</span>
          {row.category_name && (
            <Badge variant="secondary" className="shrink-0 px-1.5 py-0 text-[10px]">
              {row.category_name}
            </Badge>
          )}
        </div>
        <span className="inline-flex items-center gap-1 text-xs font-medium text-amber-700 dark:text-amber-200">
          <Clock3 className="h-3 w-3" aria-hidden="true" />
          {daysOverdueLabel(row.due_date)}
        </span>
      </div>

      {/* Amount */}
      <div className="flex shrink-0 flex-col items-end leading-tight">
        <span className="tracker-number text-sm font-semibold text-foreground">
          {fmt(asDollars(remaining > 0 ? remaining : threshold))}
        </span>
        <span className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground/65">
          remaining
        </span>
      </div>

      {/* Actions */}
      <div className="flex shrink-0 items-center gap-1">
        <Button
          size="sm"
          variant="outline"
          className="h-7 gap-1.5 px-2.5 text-xs"
          disabled={loading}
          onClick={() => onPayNow(row)}
        >
          <CreditCard className="h-3 w-3" />
          Pay now
        </Button>

        <Button
          size="sm"
          variant="ghost"
          className="h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground"
          disabled={loading}
          onClick={handleSkip}
        >
          <SkipForward className="h-3 w-3 mr-1" />
          Skip
        </Button>

        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              size="sm"
              variant="ghost"
              className="h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground"
              disabled={loading}
            >
              <BellOff className="h-3 w-3 mr-1" />
              Snooze
              <ChevronDown className="ml-0.5 h-2.5 w-2.5 opacity-60" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="min-w-[120px]">
            <DropdownMenuItem onClick={() => handleSnooze(1)}>1 day</DropdownMenuItem>
            <DropdownMenuItem onClick={() => handleSnooze(3)}>3 days</DropdownMenuItem>
            <DropdownMenuItem onClick={() => handleSnooze(7)}>7 days</DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </div>
  );
}

interface OverdueCommandCenterProps {
  rows: TrackerRow[];
  year: number;
  month: number;
  refresh: () => void;
  onPayNow: (row: TrackerRow) => void;
  // Controlled + persisted collapse state (falls back to local state when omitted).
  collapsed?: boolean;
  onCollapsedChange?: (collapsed: boolean) => void;
  // Fully hide the panel (writes the tracker_show_* setting on the page).
  onHide?: () => void;
}

export default function OverdueCommandCenter({ rows, year, month, refresh, onPayNow, collapsed, onCollapsedChange, onHide }: OverdueCommandCenterProps) {
  const todayStr = localDateString();
  const [localOpen, setLocalOpen] = useState(true);
  const isControlled = collapsed !== undefined;
  const isOpen = isControlled ? !collapsed : localOpen;
  const setOpen = (open: boolean) => {
    if (isControlled) onCollapsedChange?.(!open);
    else setLocalOpen(open);
  };

  const overdueRows = rows.filter(r =>
    (r.status === 'late' || r.status === 'missed') &&
    !r.is_skipped &&
    (!r.snoozed_until || r.snoozed_until <= todayStr)
  );

  const snoozedRows = rows.filter(r =>
    (r.status === 'late' || r.status === 'missed') &&
    !r.is_skipped &&
    r.snoozed_until && r.snoozed_until > todayStr
  );

  if (overdueRows.length === 0) return null;

  const totalOverdue = overdueRows.reduce((sum, r) => {
    const threshold = r.actual_amount ?? r.expected_amount;
    const paid = r.total_paid ?? 0;
    return sum + Math.max(0, threshold - paid);
  }, 0);

  const ToggleIcon = isOpen ? ChevronDown : ChevronUp;

  return (
    <Collapsible open={isOpen} onOpenChange={setOpen}>
      <div className="surface-premium overflow-hidden border-amber-500/30 bg-amber-500/[0.055] dark:border-amber-300/25 dark:bg-amber-400/[0.05]">

        {/* Header */}
        <div className="flex items-center gap-2 px-3 py-3 sm:px-4">
          <CollapsibleTrigger asChild>
            <button
              type="button"
              aria-expanded={isOpen}
              className="group flex min-w-0 flex-1 items-center gap-2.5 rounded-lg text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-400/45"
            >
              <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-amber-500/25 bg-amber-500/10 text-amber-700 dark:text-amber-200">
                <CalendarClock className="h-4 w-4" aria-hidden="true" />
              </span>
              <span className="min-w-0">
                <span className="block text-sm font-semibold text-foreground">
                  Review overdue bills
                </span>
                <span className="block truncate text-xs text-muted-foreground">
                  {`${overdueRows.length} ${overdueRows.length === 1 ? 'item' : 'items'} ready for pay, skip, or snooze`}
                </span>
              </span>
              <span className="tracker-number shrink-0 text-sm font-semibold text-foreground">
                {fmt(asDollars(totalOverdue))}
              </span>
              {snoozedRows.length > 0 && (
                <span className="hidden text-xs text-muted-foreground sm:inline">
                  ({snoozedRows.length} snoozed)
                </span>
              )}
              <ToggleIcon className="ml-auto h-4 w-4 shrink-0 text-muted-foreground transition-colors group-hover:text-foreground" />
            </button>
          </CollapsibleTrigger>
          {onHide && (
            <Button
              type="button"
              size="sm"
              variant="ghost"
              onClick={onHide}
              className="h-8 shrink-0 gap-1.5 px-2.5 text-xs text-muted-foreground hover:text-foreground"
              aria-label="Hide overdue panel"
            >
              <EyeOff className="h-3.5 w-3.5" />
              <span className="hidden sm:inline">Hide</span>
            </Button>
          )}
        </div>

        {/* Bill rows */}
        <CollapsibleContent>
          <div className="border-t border-border/50 px-2 pb-2 pt-1 sm:px-3">
            {overdueRows.map(row => (
              <OverdueRow
                key={row.id}
                row={row}
                year={year}
                month={month}
                onPayNow={onPayNow}
                onRefresh={refresh}
              />
            ))}
          </div>
        </CollapsibleContent>
      </div>
    </Collapsible>
  );
}
