import { updateRecord } from "@/hooks/useData";
import type { RecordSpec, DataRow } from "@/types/spec";

interface ChecklistViewProps {
  rows: DataRow[];
  rec: RecordSpec | undefined;
  titleField: string;
  checkedField: string;
  table: string;
  onViewDetail: (table: string, id: string) => void;
}

export function ChecklistView({ rows, rec, titleField, checkedField, table, onViewDetail }: ChecklistViewProps) {
  async function toggle(row: DataRow) {
    const current = Boolean(row[checkedField]);
    await updateRecord(table, String(row.id), { [checkedField]: current ? 0 : 1 });
    (row as any)[checkedField] = current ? 0 : 1;
  }

  const unchecked = rows.filter((r) => !r[checkedField]);
  const checked = rows.filter((r) => r[checkedField]);

  return (
    <div>
      <div class="space-y-1">
        {unchecked.map((row) => (
          <CheckItem key={String(row.id)} row={row} titleField={titleField} checkedField={checkedField} onToggle={() => toggle(row)} onClick={() => onViewDetail(table, String(row.id))} />
        ))}
      </div>
      {checked.length > 0 && (
        <>
          <div class="font-mono text-[var(--z-font-xs)] uppercase tracking-wider mt-5 mb-2" style={{ color: "var(--z-muted)", opacity: 0.5 }}>
            Completed ({checked.length})
          </div>
          <div class="space-y-1">
            {checked.map((row) => (
              <CheckItem key={String(row.id)} row={row} titleField={titleField} checkedField={checkedField} done onToggle={() => toggle(row)} onClick={() => onViewDetail(table, String(row.id))} />
            ))}
          </div>
        </>
      )}
    </div>
  );
}

function CheckItem({ row, titleField, checkedField, done, onToggle, onClick }: {
  row: DataRow; titleField: string; checkedField: string; done?: boolean;
  onToggle: () => void; onClick: () => void;
}) {
  return (
    <div
      class="flex items-center gap-3 rounded-[var(--z-radius-card)] transition-all cursor-pointer"
      style={{ border: "var(--z-card-border)", boxShadow: "var(--z-card-shadow)", padding: "var(--z-density-padding)" }}
      onMouseOver={(e) => { (e.currentTarget as HTMLElement).style.background = "var(--z-card-bg)"; }}
      onMouseOut={(e) => { (e.currentTarget as HTMLElement).style.background = "transparent"; }}
    >
      <input
        type="checkbox"
        checked={done}
        class="w-4 h-4 shrink-0 rounded cursor-pointer"
        style={{ accentColor: "var(--z-accent)" }}
        onClick={(e) => { e.stopPropagation(); onToggle(); }}
      />
      <span
        class={`text-[var(--z-font-md)] flex-1 ${done ? "line-through" : ""}`}
        style={{ opacity: done ? 0.4 : 1 }}
        onClick={onClick}
      >
        {String(row[titleField] || "—")}
      </span>
    </div>
  );
}
