"use client";

import { memo } from "react";
import { AlertTriangle } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { StatusBadge } from "@/components/shared/status-badge";
import { MONTHS_SHORT, formatRupiah } from "@/lib/format";
import { cn } from "@/lib/utils";
import type { ImportMonthPlan, ImportRow } from "@/types";

/** Tampilan ringkas rencana per bulan: warna = apa yang akan dibuat, huruf = isi sel Excel. */
function monthLook(plan: ImportMonthPlan | undefined): { cls: string; text: string } {
  if (!plan) return { cls: "bg-slate-50 text-slate-300", text: "" };
  const type = plan.cell.type;
  const flagged = plan.cell.issues.length > 0;
  const base = (() => {
    switch (plan.action) {
      case "invoice_paid": return { cls: "bg-emerald-100 text-emerald-800", text: plan.method === "transfer" ? "T" : plan.method?.startsWith("potong") ? "P" : "✓" };
      case "invoice_partial": return { cls: "bg-amber-100 text-amber-800", text: "½" };
      case "invoice_unpaid": return { cls: "bg-red-50 text-red-700", text: type === "unknown" ? "?" : "–" };
      case "invoice_free": return { cls: "bg-sky-100 text-sky-700", text: "F" };
      default:
        if (type === "off") return { cls: "bg-slate-200 text-slate-700", text: "OFF" };
        if (type === "install") return { cls: "bg-indigo-100 text-indigo-700", text: "+" };
        if (type === "reactivate") return { cls: "bg-indigo-100 text-indigo-700", text: "↺" };
        if (type === "unknown") return { cls: "bg-slate-100 text-slate-500", text: "?" };
        return { cls: "bg-slate-50 text-slate-300", text: "" };
    }
  })();
  return { cls: cn(base.cls, flagged && "ring-2 ring-inset ring-amber-400"), text: base.text };
}

function monthTitle(plan: ImportMonthPlan | undefined, m: number): string {
  if (!plan) return `${MONTHS_SHORT[m - 1]}: (kolom tidak ada)`;
  const lines = [`${MONTHS_SHORT[m - 1]}: ${plan.cell.raw || "(kosong)"}`];
  if (plan.action === "invoice_paid" || plan.action === "invoice_partial") lines.push(`Bayar ${formatRupiah(plan.paid_amount)} · ${plan.paid_at ?? "-"} · ${plan.method}`);
  if (plan.action === "invoice_unpaid") lines.push(`Tagihan ${formatRupiah(plan.amount)} belum dibayar`);
  plan.cell.issues.forEach((i) => lines.push(`⚠ ${i}`));
  return lines.join("\n");
}

export const ImportRowItem = memo(function ImportRowItem({ row, excluded, onToggle }: { row: ImportRow; excluded: boolean; onToggle: (id: string) => void }) {
  return (
    <li className={cn("flex gap-3 p-3 sm:p-4", excluded && "bg-slate-50 opacity-60")}>
      <input
        type="checkbox"
        className="mt-1 h-4 w-4 shrink-0 rounded border-input accent-sky-700"
        checked={!excluded}
        onChange={() => onToggle(row.id)}
        aria-label={`Import ${row.name}`}
      />
      <div className="min-w-0 flex-1 space-y-2">
        <div className="flex flex-wrap items-start justify-between gap-2">
          <div className="min-w-0">
            <p className="flex flex-wrap items-center gap-1.5 font-medium">
              {row.name}
              {row.status !== "aktif" && <StatusBadge type="customer" status={row.status} />}
              {row.existing_customer_id && <Badge variant="info">Sudah ada</Badge>}
            </p>
            <p className="text-xs text-muted-foreground">
              <span className="font-mono">{row.id}</span> · {row.area} · Tgl {String(row.due_day).padStart(2, "0")} ·{" "}
              {row.price ? formatRupiah(row.price) : <span className="text-red-600">nominal kosong</span>}
              {row.custom_price && " (khusus)"}
              {row.phone && ` · ${row.phone}`}
              {row.pppoe && ` · PPPoE ${row.pppoe}`}
            </p>
            {row.notes && <p className="text-xs italic text-muted-foreground">Catatan: {row.notes}</p>}
          </div>
        </div>

        <div className="flex gap-0.5 overflow-x-auto">
          {Array.from({ length: 12 }, (_, i) => i + 1).map((m) => {
            const plan = row.months[m];
            const look = monthLook(plan);
            return (
              <div key={m} title={monthTitle(plan, m)} className="flex w-9 shrink-0 flex-col items-center gap-0.5 sm:w-10">
                <span className="text-[9px] uppercase text-muted-foreground">{MONTHS_SHORT[m - 1]}</span>
                <span className={cn("flex h-6 w-full items-center justify-center rounded text-[10px] font-semibold", look.cls)}>{look.text}</span>
              </div>
            );
          })}
        </div>

        {row.issues.length > 0 && (
          <ul className="space-y-0.5 rounded-md bg-amber-50 p-2 text-xs text-amber-900">
            {row.issues.map((issue, i) => (
              <li key={i} className="flex gap-1.5"><AlertTriangle className="mt-0.5 h-3 w-3 shrink-0" />{issue}</li>
            ))}
          </ul>
        )}
      </div>
    </li>
  );
});

export function ImportLegend() {
  const items = [
    ["bg-emerald-100 text-emerald-800", "✓", "Lunas (T = transfer, P = potongan)"],
    ["bg-amber-100 text-amber-800", "½", "Sebagian"],
    ["bg-red-50 text-red-700", "–", "Tagihan belum dibayar"],
    ["bg-sky-100 text-sky-700", "F", "Gratis"],
    ["bg-slate-200 text-slate-700", "OFF", "Berhenti"],
    ["bg-indigo-100 text-indigo-700", "+", "Bulan pasang"],
    ["bg-white ring-2 ring-inset ring-amber-400", "", "Perlu dicek"],
  ] as const;
  return (
    <div className="flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-muted-foreground">
      {items.map(([cls, text, label]) => (
        <span key={label} className="inline-flex items-center gap-1">
          <span className={cn("flex h-4 min-w-6 items-center justify-center rounded px-0.5 text-[9px] font-semibold", cls)}>{text}</span>
          {label}
        </span>
      ))}
      <span>· Arahkan kursor ke kotak untuk melihat teks asli.</span>
    </div>
  );
}
