import Link from "next/link";
import { notFound } from "next/navigation";
import { getSubmission, transitionSubmissionStatus } from "@/lib/actions/reporting";
import { LocalTime } from "@/components/ui/LocalTime";
import { StatusBadge } from "@/components/ui/report-kit";

type Props = { params: Promise<{ id: string }> };

const SUBMISSION_TRANSITIONS: Record<string, string[]> = {
  draft: ["pending"],
  pending: ["submitted", "draft"],
  submitted: ["acknowledged", "rejected"],
  rejected: ["draft"],
  acknowledged: [],
};

const SUBMISSION_TRANSITION_LABELS: Record<string, string> = {
  pending: "Mark Pending",
  submitted: "Mark Submitted",
  acknowledged: "Acknowledge",
  rejected: "Reject",
  draft: "Return to Draft",
};

const SUBMISSION_TRANSITION_STYLES: Record<string, string> = {
  pending: "bg-[var(--dpf-accent)] text-white hover:opacity-90",
  submitted: "bg-[var(--dpf-accent)] text-white hover:opacity-90",
  acknowledged: "bg-[var(--dpf-success)] text-white hover:opacity-90",
  rejected: "bg-[var(--dpf-error)] text-white hover:opacity-90",
  draft: "bg-[var(--dpf-surface-2)] text-[var(--dpf-text)] hover:opacity-90",
};

export default async function SubmissionDetailPage({ params }: Props) {
  const { id } = await params;
  let submission;
  try {
    submission = await getSubmission(id);
  } catch {
    notFound();
  }

  const now = new Date();
  const daysRemaining = submission.dueDate
    ? Math.ceil((new Date(submission.dueDate).getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
    : null;
  const availableTransitions = SUBMISSION_TRANSITIONS[submission.status] ?? [];

  return (
    <div>
      {/* Breadcrumb */}
      <div className="mb-2">
        <Link href="/compliance/submissions" className="text-xs text-[var(--dpf-muted)] hover:text-[var(--dpf-text)]">Submissions</Link>
        <span className="text-xs text-[var(--dpf-muted)]"> / </span>
        <span className="text-xs text-[var(--dpf-text)]">{submission.title}</span>
      </div>

      <div className="mb-6">
        <div className="flex items-center gap-2 mb-1">
          <h1 className="text-xl font-bold text-[var(--dpf-text)]">{submission.title}</h1>
          <StatusBadge domain="complianceSubmission" status={submission.status} variant="soft" uppercase={false} />
        </div>
        <p className="text-sm text-[var(--dpf-muted)]">{submission.recipientBody} · {submission.submissionType}</p>
      </div>

      {/* Status Transitions */}
      {availableTransitions.length > 0 && (
        <div className="flex items-center gap-2 mb-6">
          <span className="text-xs text-[var(--dpf-muted)] mr-1">Transition:</span>
          {availableTransitions.map((target) => (
            <form key={target} action={async () => { "use server"; await transitionSubmissionStatus(id, target); }}>
              <button type="submit"
                className={`px-3 py-1.5 text-xs font-medium rounded ${SUBMISSION_TRANSITION_STYLES[target] ?? "bg-[var(--dpf-accent)] text-white hover:opacity-90"}`}>
                {SUBMISSION_TRANSITION_LABELS[target] ?? target}
              </button>
            </form>
          ))}
        </div>
      )}

      {/* Metadata */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-6">
        {submission.dueDate && (
          <div className="p-3 rounded-lg border border-[var(--dpf-border)]">
            <p className="text-xs text-[var(--dpf-muted)]">Due Date</p>
            <p className={`text-sm font-semibold ${daysRemaining !== null && daysRemaining < 0 ? "text-[var(--dpf-error)]" : daysRemaining !== null && daysRemaining < 7 ? "text-[var(--dpf-warning)]" : "text-[var(--dpf-text)]"}`}>
              <LocalTime value={submission.dueDate} utc />
              {daysRemaining !== null && (
                <span className="text-xs ml-1">({daysRemaining < 0 ? `${Math.abs(daysRemaining)}d overdue` : `${daysRemaining}d remaining`})</span>
              )}
            </p>
          </div>
        )}
        {submission.submittedAt && (
          <div className="p-3 rounded-lg border border-[var(--dpf-border)]">
            <p className="text-xs text-[var(--dpf-muted)]">Submitted</p>
            <LocalTime value={submission.submittedAt} mode="date" className="text-sm font-semibold text-[var(--dpf-text)]" />
          </div>
        )}
        {submission.confirmationRef && (
          <div className="p-3 rounded-lg border border-[var(--dpf-border)]">
            <p className="text-xs text-[var(--dpf-muted)]">Confirmation</p>
            <p className="text-sm font-semibold text-[var(--dpf-text)]">{submission.confirmationRef}</p>
          </div>
        )}
        {submission.submittedBy && (
          <div className="p-3 rounded-lg border border-[var(--dpf-border)]">
            <p className="text-xs text-[var(--dpf-muted)]">Submitted By</p>
            <p className="text-sm font-semibold text-[var(--dpf-text)]">{submission.submittedBy.displayName}</p>
          </div>
        )}
      </div>

      {/* Regulation link */}
      {submission.regulation ? (
        <p className="text-xs text-[var(--dpf-info)] mb-6">
          Regulation:{" "}
          <a href={`/compliance/regulations/${submission.regulation.id}`} className="underline">
            {submission.regulation.name} ({submission.regulation.shortName})
          </a>
        </p>
      ) : (
        <p className="text-xs text-[var(--dpf-muted)] mb-6">No linked regulation.</p>
      )}

      {/* Preparation Checklist */}
      <h2 className="text-xs text-[var(--dpf-muted)] uppercase tracking-widest mb-3">Preparation Checklist</h2>
      {submission.checklist.length === 0 ? (
        <p className="text-sm text-[var(--dpf-muted)] mb-6">No obligations to check (no linked regulation or no obligations defined).</p>
      ) : (
        <div className="space-y-2 mb-6">
          {submission.checklist.map((item: { obligationId: string; title: string; hasEvidence: boolean; evidenceCount: number }) => (
            <div key={item.obligationId} className="p-3 rounded-lg border border-[var(--dpf-border)] flex items-center justify-between">
              <div className="flex items-center gap-2">
                <span className="w-2 h-2 rounded-full" style={{ backgroundColor: item.hasEvidence ? "var(--dpf-success)" : "var(--dpf-error)" }} />
                <span className="text-sm text-[var(--dpf-text)]">{item.title}</span>
              </div>
              <span className="text-xs text-[var(--dpf-muted)]">{item.evidenceCount} evidence record{item.evidenceCount !== 1 ? "s" : ""}</span>
            </div>
          ))}
        </div>
      )}

      {submission.notes && (
        <div className="mb-6">
          <h2 className="text-xs text-[var(--dpf-muted)] uppercase tracking-widest mb-2">Notes</h2>
          <p className="text-sm text-[var(--dpf-text)]">{submission.notes}</p>
        </div>
      )}
    </div>
  );
}
