﻿"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { CalendarIcon, DownloadIcon, FileTextIcon, ShieldCheckIcon, UsersIcon } from "@/components/dashboard-icons";
import {
  buildRapItemSummary,
  cloneRapItems,
  formatPoDiff,
  getRapStatusClass,
  getRapStatusLabel,
  type CustomerPoRapWorkspace,
  type RapStatus,
} from "@/lib/customer-po-rap-data";
import { formatRupiah } from "@/lib/crm-pages-data";
import { cn } from "@/lib/utils";

type FeedbackState = {
  kind: "success" | "warning" | "error";
  message: string;
};

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>;
}

function toNumeric(value: string) {
  const digits = value.replace(/[^\d]/g, "");
  return digits ? Number(digits) : 0;
}

export function RapOperationalReviewWorkspace({ workspace }: { workspace: CustomerPoRapWorkspace }) {
  const [status, setStatus] = useState<RapStatus>(workspace.rap.status);
  const [items, setItems] = useState(() => cloneRapItems(workspace.rap.items));
  const [notes, setNotes] = useState(workspace.rap.operationalNotes ?? "");
  const [feedback, setFeedback] = useState<FeedbackState | null>(null);
  const [justSubmitted, setJustSubmitted] = useState(false);
  const originalItems = workspace.rap.items;

  const summary = useMemo(() => buildRapItemSummary(items), [items]);
  const isEditable = status === "pending_operational_review";
  const isPendingApproval = status === "pending_approval";

  function updatePlafon(itemId: string, value: string) {
    if (!isEditable) {
      return;
    }

    setItems((current) =>
      current.map((item) =>
        item.id === itemId
          ? {
              ...item,
              plafonAmount: toNumeric(value),
            }
          : item,
      ),
    );
  }

  function handleSaveProgress() {
    if (!isEditable) {
      return;
    }

    setFeedback({
      kind: "success",
      message: "Progress Update RAP tersimpan. Perubahan plafon dan catatan dapat dilanjutkan kapan saja.",
    });
  }

  function handleSubmitToManagement() {
    if (!isEditable) {
      return;
    }

    if (items.some((item) => item.plafonAmount <= 0)) {
      setFeedback({ kind: "error", message: "Semua plafon_amount per item wajib diisi sebelum diajukan ke management." });
      return;
    }

    setStatus("pending_approval");
    setJustSubmitted(true);
    setFeedback({
      kind: "success",
      message: "RAP berhasil diajukan ke Management Approval 3-tier. Penguncian anggaran akan aktif setelah 3 approver setuju.",
    });
  }

  const diff = summary.totalBudgetModal - summary.totalBoqCost;
  const statusLabel = getRapStatusLabel(status);
  const statusClass = getRapStatusClass(status);
  const changesCount = items.filter((item) => item.plafonAmount !== (originalItems.find((origin) => origin.id === item.id)?.plafonAmount ?? item.plafonAmount)).length;

  if (!isEditable) {
    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">Update RAP</h2>
          </div>

          <div className="flex w-full flex-col gap-2 sm:flex-row lg:w-auto">
            <Link href={`/rap/${workspace.rap.rapId}`} className={buttonVariants({ variant: "outline", className: "w-full sm:w-auto" })}>
              Open RAP detail
            </Link>
            <Link href="/rap-approvals" className={buttonVariants({ variant: "outline", className: "w-full sm:w-auto" })}>
              Open approval queue
            </Link>
          </div>
        </div>

        <Card>
          <CardContent className="space-y-4 p-5">
            <div className="flex items-start justify-between gap-4">
              <div>
                <p className="text-sm text-muted-foreground">Status workspace</p>
                <div className="mt-2 flex flex-wrap gap-2">
                  <Badge label={statusLabel} className={statusClass} />
                  <Badge
                    label={status === "locked" ? "Locked" : status === "pending_approval" ? "Menunggu approval" : "Perlu revisi"}
                    className={status === "locked" ? "bg-emerald-100 text-emerald-700" : status === "pending_approval" ? "bg-sky-100 text-sky-700" : "bg-rose-100 text-rose-700"}
                  />
                </div>
              </div>
              <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
                <ShieldCheckIcon className="h-5 w-5" />
              </div>
            </div>

            <p className="text-sm text-muted-foreground">
              {status === "locked"
                ? "RAP sudah terkunci. Lanjutkan ke Purchase Request untuk eksekusi procurement."
                : status === "pending_approval"
                  ? "RAP sudah masuk management approval 3-tier dan menunggu keputusan para approver."
                  : "RAP perlu direvisi sebelum bisa diajukan kembali."}
            </p>
            {justSubmitted ? (
              <div
                className={cn(
                  "fixed bottom-6 right-6 z-50 flex w-80 items-start gap-3 rounded-xl border px-4 py-3 text-sm shadow-[0_20px_60px_rgba(0,0,0,0.15)] backdrop-blur-sm border-emerald-200 bg-emerald-50/95 text-emerald-800",
                )}
              >
                <div className="flex-1">
                  <div className="flex items-start gap-3">
                    <ShieldCheckIcon className="mt-0.5 h-4 w-4 shrink-0" />
                    <span>RAP berhasil diajukan ke management approval.</span>
                  </div>
                </div>
                <button type="button" onClick={() => setJustSubmitted(false)} className="shrink-0 text-muted-foreground hover:text-foreground">&times;</button>
              </div>
            ) : null}
          </CardContent>
        </Card>
      </div>
    );
  }

  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">Update RAP</h2>
        </div>

        <div className="flex w-full flex-col gap-2 sm:flex-row lg:w-auto">
          <Link href={`/rap/${workspace.rap.rapId}`} className={buttonVariants({ variant: "outline", className: "w-full sm:w-auto" })}>
            Open RAP detail
          </Link>
          <Link href="/rap-approvals" className={buttonVariants({ variant: "outline", className: "w-full sm:w-auto" })}>
            Open approval queue
          </Link>
        </div>
      </div>

      <Card>
        <CardContent className="space-y-4 p-4 md:p-5">
          <div className="flex items-start justify-between gap-4">
            <div>
              <p className="text-sm text-muted-foreground">Info Opportunity, BOQ, PO</p>
              <div className="mt-2 text-lg font-semibold tracking-tight">{workspace.projectName}</div>
              <p className="mt-1 text-sm text-muted-foreground">{workspace.customerName}</p>
            </div>
            <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
              <UsersIcon className="h-5 w-5" />
            </div>
          </div>

          <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
            <div className="rounded-2xl border border-border/70 bg-muted/30 px-4 py-3">
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Opportunity</p>
              <p className="mt-1 text-sm font-semibold text-foreground">{workspace.opportunityCode}</p>
            </div>
            <div className="rounded-2xl border border-border/70 bg-muted/30 px-4 py-3">
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Quotation</p>
              <p className="mt-1 text-sm font-semibold text-foreground">{workspace.quotationNumber}</p>
            </div>
            <div className="rounded-2xl border border-border/70 bg-muted/30 px-4 py-3">
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">BOQ</p>
              <p className="mt-1 text-sm font-semibold text-foreground">{workspace.boqCode}</p>
            </div>
            <div className="rounded-2xl border border-border/70 bg-muted/30 px-4 py-3">
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">PO value</p>
              <p className="mt-1 text-sm font-semibold text-foreground">{workspace.customerPo ? formatRupiah(workspace.customerPo.poValue) : "-"}</p>
            </div>
          </div>

          <div className="grid gap-3 sm:grid-cols-2">
            <div className="rounded-2xl border border-border/70 bg-background px-4 py-3">
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">RAP status</p>
              <div className="mt-2 flex flex-wrap gap-2">
                <Badge label={statusLabel} className={statusClass} />
              </div>
            </div>
            <div className="rounded-2xl border border-border/70 bg-background px-4 py-3">
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Change count</p>
              <p className="mt-2 text-sm font-semibold text-foreground">{changesCount} item disesuaikan</p>
              <p className="mt-1 text-xs text-muted-foreground">Bandingkan plafon awal Sales dengan hasil review Operasional.</p>
            </div>
          </div>

          {workspace.rap.operationalReviewedBy ? (
            <div className="rounded-2xl border border-border/70 bg-muted/20 px-4 py-3 text-sm text-muted-foreground">
              <div className="grid gap-2 md:grid-cols-3">
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Reviewed by</p>
                  <p className="mt-1 font-semibold text-foreground">{workspace.rap.operationalReviewedBy}</p>
                </div>
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Reviewed at</p>
                  <p className="mt-1 font-semibold text-foreground">{workspace.rap.operationalReviewedAt ? new Date(workspace.rap.operationalReviewedAt).toLocaleString("id-ID") : "-"}</p>
                </div>
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Submitted at</p>
                  <p className="mt-1 font-semibold text-foreground">{workspace.rap.submittedAt ? new Date(workspace.rap.submittedAt).toLocaleString("id-ID") : "-"}</p>
                </div>
              </div>
            </div>
          ) : null}
        </CardContent>
      </Card>

      <Card>
        <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">
            <CardTitle className="text-lg">Tabel Item RAP</CardTitle>
            <Button variant="outline" className="h-9 w-full px-3 sm:w-auto">
              <DownloadIcon className="mr-1.5 h-3.5 w-3.5" />
              Export RAP
            </Button>
          </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">Item</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Qty</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Unit</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Harga modal BOQ</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Plafon anggaran</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Subtotal plafon</th>
                </tr>
              </thead>
              <tbody>
                {items.map((item) => {
                  const originalItem = originalItems.find((origin) => origin.id === item.id) ?? item;
                  const adjusted = originalItem.plafonAmount !== item.plafonAmount;

                  return (
                    <tr key={item.id} className="transition hover:bg-accent/60">
                      <td className="border-b border-border/70 px-5 py-4 align-top">
                        <div className="flex items-start justify-between gap-2">
                          <div>
                            <div className="font-semibold text-foreground">{item.itemName}</div>
                            <div className="mt-1 text-xs text-muted-foreground">{item.boqItemId}</div>
                          </div>
                          {adjusted ? <Badge label="Disesuaikan" className="bg-amber-100 text-amber-700" /> : null}
                        </div>
                      </td>
                      <td className="border-b border-border/70 px-5 py-4 align-top font-medium">{item.quantity}</td>
                      <td className="border-b border-border/70 px-5 py-4 align-top text-muted-foreground">{item.unit}</td>
                      <td className="border-b border-border/70 px-5 py-4 align-top font-medium">{formatRupiah(item.unitCostBoq)}</td>
                      <td className="border-b border-border/70 px-5 py-4 align-top">
                        <input
                          value={String(item.plafonAmount)}
                          onChange={(event) => updatePlafon(item.id, event.target.value)}
                          disabled={!isEditable}
                          className="h-11 w-full rounded-xl border border-border/80 bg-background px-3 text-sm outline-none transition focus:border-blue-500 focus:ring-2 focus:ring-blue-200 disabled:cursor-not-allowed disabled:bg-muted/40"
                        />
                        {adjusted ? (
                          <p
                            className="mt-2 text-xs text-muted-foreground"
                            title={`Awal ${formatRupiah(originalItem.plafonAmount)} menjadi ${formatRupiah(item.plafonAmount)}`}
                          >
                            Awal {formatRupiah(originalItem.plafonAmount)} menjadi {formatRupiah(item.plafonAmount)}
                          </p>
                        ) : null}
                      </td>
                      <td className="border-b border-border/70 px-5 py-4 align-top font-medium">{formatRupiah(item.plafonAmount)}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Catatan Penyesuaian</CardTitle>
          <p className="mt-1 text-sm text-muted-foreground">Opsional, tetapi sangat disarankan untuk menjelaskan perubahan plafon dari usulan Sales.</p>
        </CardHeader>
        <CardContent className="space-y-4">
          <textarea
            rows={5}
            value={notes}
            onChange={(event) => setNotes(event.target.value)}
            disabled={!isEditable}
            placeholder="Contoh: item kelistrikan tambahan karena layout lapangan berubah..."
            className="w-full rounded-3xl border border-border/80 bg-background px-4 py-3 text-sm outline-none transition placeholder:text-muted-foreground focus:border-blue-500 focus:ring-2 focus:ring-blue-200 disabled:cursor-not-allowed disabled:bg-muted/40"
          />

          <div className="grid gap-3 md:grid-cols-3">
            <div className="rounded-2xl border border-border/70 bg-muted/20 px-4 py-3">
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Total plafon RAP</p>
              <p className="mt-1 text-sm font-semibold text-foreground">{formatRupiah(summary.totalBudgetModal)}</p>
            </div>
            <div className="rounded-2xl border border-border/70 bg-muted/20 px-4 py-3">
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Total modal BOQ</p>
              <p className="mt-1 text-sm font-semibold text-foreground">{formatRupiah(summary.totalBoqCost)}</p>
            </div>
            <div className="rounded-2xl border border-border/70 bg-muted/20 px-4 py-3">
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Selisih</p>
              <p className="mt-1 text-sm font-semibold text-foreground">{diff === 0 ? "Rp 0" : `${diff > 0 ? "+" : "-"}${formatRupiah(Math.abs(diff))}`}</p>
            </div>
          </div>

          <div className={cn("rounded-2xl border px-4 py-3 text-sm", diff === 0 ? "border-emerald-200 bg-emerald-50 text-emerald-800" : "border-amber-200 bg-amber-50 text-amber-800")}>
            <div className="flex items-start gap-2">
              <CalendarIcon className="mt-0.5 h-4 w-4 shrink-0" />
              <span>
                {diff === 0
                  ? "Total plafon RAP konsisten dengan total modal BOQ."
                  : `Total plafon RAP berbeda ${formatPoDiff(diff)} dari total modal BOQ. Pastikan catatan penyesuaian jelas sebelum diajukan.`}
              </span>
            </div>
          </div>

          {feedback ? (
            <div
              className={cn(
                "fixed bottom-6 right-6 z-50 flex w-80 items-start gap-3 rounded-xl border px-4 py-3 text-sm shadow-[0_20px_60px_rgba(0,0,0,0.15)] backdrop-blur-sm",
                feedback.kind === "success" && "border-emerald-200 bg-emerald-50/95 text-emerald-800",
                feedback.kind === "warning" && "border-amber-200 bg-amber-50/95 text-amber-800",
                feedback.kind === "error" && "border-rose-200 bg-rose-50/95 text-rose-800",
              )}
            >
              <div className="flex-1">
                <div className="flex items-start gap-3">
                  <ShieldCheckIcon className="mt-0.5 h-4 w-4 shrink-0" />
                  <span>{feedback.message}</span>
                </div>
              </div>
              <button type="button" onClick={() => setFeedback(null)} className="shrink-0 text-muted-foreground hover:text-foreground">&times;</button>
            </div>
          ) : null}

          <div className="flex flex-wrap gap-2">
            <Button onClick={handleSaveProgress} disabled={!isEditable} className="h-11 px-4">
              Simpan progres
            </Button>
            <Button
              variant="outline"
              onClick={handleSubmitToManagement}
              disabled={!isEditable}
              className="h-11 gap-2 border-sky-300 bg-sky-50/80 px-4 text-sky-700 shadow-sm shadow-sky-950/5 hover:border-sky-400 hover:bg-sky-100/90 disabled:cursor-not-allowed disabled:opacity-50"
            >
              <FileTextIcon className="h-4 w-4" />
              <span>Setujui & Ajukan ke Management</span>
            </Button>
            <Link
              href="/rap-approvals"
              className={buttonVariants({
                variant: "outline",
                className: "h-11 gap-2 border-emerald-300 bg-emerald-50/80 px-4 text-emerald-700 shadow-sm shadow-emerald-950/5 hover:border-emerald-400 hover:bg-emerald-100/90",
              })}
            >
              <ShieldCheckIcon className="h-4 w-4" />
              <span>Buka Approval Queue</span>
            </Link>
          </div>

          {isPendingApproval ? (
            <div className="rounded-xl bg-emerald-50/80 px-4 py-4 text-sm text-emerald-900">
              <p className="font-semibold">RAP sudah diajukan ke management approval.</p>
              <p className="mt-1 text-sm text-emerald-900/80">Proses berikutnya berada di antrian 3-tier approval RAP.</p>
            </div>
          ) : null}
        </CardContent>
      </Card>
    </div>
  );
}
