"use client";

import { useState } from "react";
import { Send, Pencil, Trash2, Loader2 } from "lucide-react";

export interface ScheduleDto {
  id: string;
  name: string;
  frequency: string;
  dayOfWeek: number | null;
  dayOfMonth: number | null;
  timeOfDay: string;
  recipients: string[];
  sections: string[];
  includeAiAnalysis: boolean;
  includeCompetitorScan: boolean;
  includeMarketInsights: boolean;
  isActive: boolean;
  lastSentAt: string | null;
  nextSendAt: string | null;
  _count?: { sentReports: number };
}

const FREQ_BADGE: Record<string, { label: string; cls: string }> = {
  daily: { label: "Daily", cls: "bg-blue-50 text-blue-700 border-blue-200" },
  weekly: { label: "Weekly", cls: "bg-green-50 text-green-700 border-green-200" },
  biweekly: { label: "Bi-Weekly", cls: "bg-violet-50 text-violet-700 border-violet-200" },
  monthly: { label: "Monthly", cls: "bg-orange-50 text-orange-700 border-orange-200" },
};
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

interface Props {
  schedule: ScheduleDto;
  onSendNow: (id: string) => Promise<void>;
  onToggle: (id: string, isActive: boolean) => void;
  onEdit: (schedule: ScheduleDto) => void;
  onDelete: (id: string) => void;
}

export default function ScheduleCard({ schedule: s, onSendNow, onToggle, onEdit, onDelete }: Props) {
  const [sending, setSending] = useState(false);
  const badge = FREQ_BADGE[s.frequency] ?? FREQ_BADGE.weekly;

  const detailParts: string[] = [];
  if ((s.frequency === "weekly" || s.frequency === "biweekly") && s.dayOfWeek != null) detailParts.push(`Every ${s.frequency === "biweekly" ? "other " : ""}${DAYS[s.dayOfWeek]}`);
  if (s.frequency === "monthly" && s.dayOfMonth != null) detailParts.push(`Day ${s.dayOfMonth}`);
  detailParts.push(`${s.timeOfDay} UTC`);

  async function handleSendNow() {
    setSending(true);
    try { await onSendNow(s.id); } finally { setSending(false); }
  }

  const maxShow = 3;
  const extraRecipients = s.recipients.length - maxShow;

  return (
    <div className={`bg-white rounded-xl border border-slate-200 overflow-hidden ${!s.isActive ? "opacity-60" : ""}`}>
      <div className="px-5 py-4">
        <div className="flex items-start justify-between mb-2">
          <div>
            <h3 className="text-sm font-bold text-slate-900">{s.name}</h3>
            <div className="flex items-center gap-2 mt-1.5">
              <span className={`px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wide border ${badge.cls}`}>{badge.label}</span>
              <span className="text-[11px] text-slate-500">{detailParts.join(" · ")}</span>
            </div>
          </div>
          {/* Active toggle */}
          <button onClick={() => onToggle(s.id, !s.isActive)} className={`relative w-9 h-5 rounded-full transition-colors shrink-0 ${s.isActive ? "bg-brand-600" : "bg-slate-200"}`}>
            <span className={`absolute top-0.5 ${s.isActive ? "left-4" : "left-0.5"} w-4 h-4 bg-white rounded-full shadow-sm transition-all`} />
          </button>
        </div>

        {/* Recipients */}
        <div className="flex flex-wrap items-center gap-1.5 mt-3">
          {s.recipients.slice(0, maxShow).map((e) => (
            <span key={e} className="px-2 py-0.5 rounded-md bg-slate-100 text-[11px] font-medium text-slate-600 truncate max-w-[180px]">{e}</span>
          ))}
          {extraRecipients > 0 && (
            <span className="text-[11px] text-slate-400">+{extraRecipients} more</span>
          )}
        </div>

        {/* Timing info */}
        <div className="flex items-center gap-4 mt-3 text-[11px] text-slate-500">
          {s.nextSendAt && (
            <span>Next: <span className="font-semibold text-slate-700">{new Date(s.nextSendAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })} at {s.timeOfDay} UTC</span></span>
          )}
          {s.lastSentAt ? (
            <span>Last sent: {new Date(s.lastSentAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })}</span>
          ) : (
            <span className="text-slate-400 italic">Never sent</span>
          )}
        </div>
      </div>

      {/* Actions */}
      <div className="flex items-center gap-2 border-t border-slate-100 px-5 py-2.5 bg-slate-50/60">
        <button onClick={handleSendNow} disabled={sending} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-brand-600 text-white text-[11px] font-semibold hover:bg-brand-700 disabled:opacity-60">
          {sending ? <Loader2 className="w-3 h-3 animate-spin" /> : <Send className="w-3 h-3" />}
          {sending ? "Sending…" : "Send Now"}
        </button>
        <button onClick={() => onEdit(s)} className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-slate-200 text-[11px] font-semibold text-slate-600 hover:bg-white">
          <Pencil className="w-3 h-3" /> Edit
        </button>
        <button onClick={() => { if (confirm(`Delete "${s.name}"?`)) onDelete(s.id); }} className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-slate-200 text-[11px] font-semibold text-red-600 hover:bg-red-50 hover:border-red-200 ml-auto">
          <Trash2 className="w-3 h-3" /> Delete
        </button>
      </div>
    </div>
  );
}
