﻿"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { SearchIcon, ShieldCheckIcon } from "@/components/dashboard-icons";
import {
  getPendingRapApprovalRows,
  getRapApprovalDecisionSummary,
  getRapApprovalPeerSummary,
  getRapApprovalRoleLabel,
} from "@/lib/rap-approval-data";
import { formatRupiah } from "@/lib/crm-pages-data";
import { cn } from "@/lib/utils";
import { Pagination } from "@/components/ui/pagination";

function Badge({ label, className }: { label: string; className: string }) {
  return <span className={cn("inline-flex rounded-full px-2.5 py-1 text-xs font-semibold", className)}>{label}</span>;
}

export function RapApprovalQueue() {
  const pendingRows = useMemo(() => getPendingRapApprovalRows(), []);

  const [page, setPage] = useState(1);
  const pageSize = 5;
  const totalPages = Math.ceil(pendingRows.length / pageSize);
  const paginatedRows = pendingRows.slice((page - 1) * pageSize, page * pageSize);

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
        <div>
          <h2 className="text-2xl font-semibold tracking-tight md:text-3xl">RAP Approval</h2>
        </div>

      </div>

      <Card className="overflow-hidden">
        <CardHeader className="p-0 md:p-0 px-8 md:px-8 pt-4 pb-1 md:pt-5 md:pb-1.5">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <CardTitle className="text-lg">Pending RAP approvals</CardTitle>
            </div>

            <label className="relative flex items-center">
              <SearchIcon className="pointer-events-none absolute left-3 h-4 w-4 text-muted-foreground" />
              <input
                type="search"
                placeholder="Search..."
                className="h-9 w-64 rounded-2xl border border-border/80 bg-background pl-9 pr-4 text-sm outline-none transition placeholder:text-muted-foreground focus:border-primary/40 focus:ring-2 focus:ring-primary/10"
              />
            </label>
          </div>
        </CardHeader>

        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="min-w-full border-separate border-spacing-0 text-left text-sm">
              <thead className="sticky top-0 bg-card/95 text-xs uppercase tracking-[0.2em] text-muted-foreground backdrop-blur">
                <tr>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">RAP</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Project</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Total plafon</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Operasional</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Status lain</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Action</th>
                </tr>
              </thead>
              <tbody>
                {pendingRows.length ? (
                  paginatedRows.map((record) => {
                    const actionHref = `/rap-approvals/${record.id}`;
                    const summary = getRapApprovalDecisionSummary(record);

                    return (
                      <tr key={record.id} className="transition hover:bg-accent/60">
                        <td className="border-b border-border/70 px-5 py-4 align-top">
                          <div className="font-semibold text-foreground">{record.rapCode}</div>
                          <div className="mt-1 text-xs text-muted-foreground">Approval ID {record.id}</div>
                          <div className="mt-1 text-xs text-muted-foreground">Approver {getRapApprovalRoleLabel(record.approverRole)}</div>
                        </td>
                        <td className="border-b border-border/70 px-5 py-4 align-top">
                          <div className="font-semibold text-foreground">{record.projectName}</div>
                          <div className="mt-1 text-xs text-muted-foreground">{record.customerName}</div>
                        </td>
                        <td className="border-b border-border/70 px-5 py-4 align-top font-medium">{formatRupiah(record.totalBudgetModal)}</td>
                        <td className="border-b border-border/70 px-5 py-4 align-top">
                          <div className="font-medium text-foreground">{record.operationalReviewedBy ?? "-"}</div>
                          <div className="mt-1 text-xs text-muted-foreground">
                            {record.operationalReviewedAt ? new Date(record.operationalReviewedAt).toLocaleString("id-ID") : "Belum direview"}
                          </div>
                        </td>
                        <td className="border-b border-border/70 px-5 py-4 align-top">
                          <Badge label={summary} className="bg-slate-100 text-slate-700" />
                          <div className="mt-2 text-xs text-muted-foreground">{getRapApprovalPeerSummary(record)}</div>
                        </td>
                        <td className="border-b border-border/70 px-5 py-4 align-top">
                          <Link
                            href={actionHref}
                            className={buttonVariants({
                              variant: "outline",
                              size: "sm",
                              className:
                                "h-10 gap-2 border-emerald-300 bg-emerald-50/80 px-3 text-emerald-700 shadow-sm shadow-emerald-950/5 hover:border-emerald-400 hover:bg-emerald-100/90",
                            })}
                          >
                            <ShieldCheckIcon className="h-4 w-4 stroke-[2.25]" />
                            <span>Review</span>
                          </Link>
                        </td>
                      </tr>
                    );
                  })
                ) : (
                  <tr>
                    <td className="px-5 py-8 text-center text-sm text-muted-foreground" colSpan={6}>
                      Tidak ada RAP menunggu approval Anda.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          <Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
        </CardContent>
      </Card>

    </div>
  );
}
