﻿"use client";

import { useEffect, 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, DollarSignIcon, DownloadIcon, FileTextIcon, SearchIcon, ShieldCheckIcon, UsersIcon } from "@/components/dashboard-icons";
import {
  buildRapItemSummary,
  cloneRapItems,
  getCustomerPoStatus,
  getCustomerPoStatusClass,
  getCustomerPoStatusLabel,
  getRapStatusClass,
  getRapStatusLabel,
  type CustomerPoRapWorkspace,
  type RapItemCategory,
  type RapStatus,
} from "@/lib/customer-po-rap-data";
import { getPurchaseRequestByRapNumber } from "@/lib/purchase-request-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;
}

const categorySections: { key: RapItemCategory; label: string; color: string }[] = [
  { key: "material_utama",   label: "Material Utama",   color: "border-blue-400" },
  { key: "material_support", label: "Material Support", color: "border-emerald-400" },
  { key: "servis",           label: "Servis / Jasa",    color: "border-violet-400" },
];

export function RapWorkspace({ workspace }: { workspace: CustomerPoRapWorkspace }) {
  const [items, setItems] = useState(() => cloneRapItems(workspace.rap.items));
  const [status, setStatus] = useState<RapStatus>(workspace.rap.status);
  const [feedback, setFeedback] = useState<FeedbackState | null>(null);
  const [expandedSections, setExpandedSections] = useState<Record<RapItemCategory, boolean>>({
    material_utama: true,
    material_support: true,
    servis: true,
  });

  function toggleSection(key: RapItemCategory) {
    setExpandedSections((prev) => ({ ...prev, [key]: !prev[key] }));
  }

  const customerPoStatus = useMemo(() => getCustomerPoStatus(workspace), [workspace]);
  const summary = useMemo(() => buildRapItemSummary(items), [items]);
  const isReadOnly = status !== "draft";

  useEffect(() => {
    document.body.style.overflow = "";
    return () => {
      document.body.style.overflow = "";
    };
  }, []);

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

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

  function handleSaveProgress() {
    if (isReadOnly) {
      return;
    }

    setFeedback({ kind: "success", message: "Progress RAP tersimpan." });
  }

  function handleSubmit() {
    if (customerPoStatus !== "saved") {
      setFeedback({ kind: "error", message: "Customer PO harus valid sebelum RAP diajukan ke Operasional." });
      return;
    }

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

    setStatus("pending_operational_review");
    setFeedback({ kind: "success", message: "RAP diajukan ke Operasional untuk Update RAP." });
  }

  const statusClass = getRapStatusClass(status);
  const statusLabel = getRapStatusLabel(status);
  const poStatusClass = getCustomerPoStatusClass(customerPoStatus);
  const poStatusLabel = getCustomerPoStatusLabel(customerPoStatus);
  const linkedPurchaseRequest = getPurchaseRequestByRapNumber(workspace.rap.rapCode);
  const diff = summary.totalBudgetModal - summary.totalBoqCost;

  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">Generate & Edit RAP</h2>
        </div>

      </div>

      <Card className="overflow-hidden">
        <div className="bg-gradient-to-r from-primary/5 via-primary/[0.02] to-transparent px-5 pb-5 pt-5 md:px-6">
          <div className="flex items-start justify-between gap-4">
            <div className="min-w-0 flex-1">
              <p className="text-xs font-medium uppercase tracking-[0.15em] text-primary/60">Info Opportunity, BOQ & PO</p>
              <h2 className="mt-1.5 text-xl font-bold tracking-tight text-foreground">{workspace.projectName}</h2>
              <p className="mt-0.5 text-sm text-muted-foreground">{workspace.customerName}</p>
            </div>
            <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary shadow-sm">
              <UsersIcon className="h-5 w-5" />
            </div>
          </div>
        </div>

        <div className="divide-y divide-border/40 px-5 py-4 md:px-6">
          <div className="grid gap-x-8 gap-y-4 pb-4 sm:grid-cols-2 xl:grid-cols-4">
            <div>
              <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Opportunity</p>
              <p className="mt-1 font-semibold">{workspace.opportunityCode}</p>
            </div>
            <div>
              <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Quotation</p>
              <p className="mt-1 font-semibold">{workspace.quotationNumber}</p>
            </div>
            <div>
              <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">BOQ</p>
              <p className="mt-1 font-semibold">{workspace.boqCode}</p>
            </div>
            <div>
              <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">PO value</p>
              <p className="mt-1 font-semibold">{workspace.customerPo ? formatRupiah(workspace.customerPo.poValue) : "-"}</p>
            </div>
            <div>
              <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Customer PO status</p>
              <div className="mt-1">
                <Badge label={poStatusLabel} className={poStatusClass} />
              </div>
            </div>
            <div>
              <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">RAP status</p>
              <div className="mt-1">
                <Badge label={statusLabel} className={statusClass} />
              </div>
            </div>
          </div>

          {workspace.customerPo ? (
            <div className="flex flex-wrap gap-x-8 gap-y-2 pt-4 text-sm">
              <div>
                <span className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">PO Number</span>
                <p className="mt-0.5 font-semibold text-foreground">{workspace.customerPo.poNumber}</p>
              </div>
              <div>
                <span className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">PO Date</span>
                <p className="mt-0.5 font-semibold text-foreground">{workspace.customerPo.poDate}</p>
              </div>
              <div>
                <span className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Saved at</span>
                <p className="mt-0.5 font-semibold text-foreground">{new Date(workspace.customerPo.savedAt).toLocaleString("id-ID")}</p>
              </div>
            </div>
          ) : null}
        </div>
      </Card>

      <Card className="overflow-hidden">
        <CardHeader className="p-0 md:p-0 px-5 md:px-6 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>
            <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>
            <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="divide-y divide-border/70">
            {categorySections.map((section) => {
              const sectionItems = items.filter((item) => item.category === section.key);
              return (
                <div key={section.key} className={cn("border-l-4", section.color)}>
                  <div className="flex items-center justify-between px-5 py-4">
                    <button
                      type="button"
                      onClick={() => toggleSection(section.key)}
                      className="flex items-center gap-3 text-left transition hover:opacity-70"
                    >
                      <svg
                        className={cn(
                          "h-4 w-4 text-muted-foreground transition-transform duration-200",
                          expandedSections[section.key] && "rotate-90",
                        )}
                        fill="none"
                        viewBox="0 0 24 24"
                        strokeWidth={2.5}
                        stroke="currentColor"
                      >
                        <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
                      </svg>
                      <span className="font-semibold text-foreground">{section.label}</span>
                      <span className="rounded-full bg-muted px-2.5 py-0.5 text-xs font-medium text-muted-foreground">
                        {sectionItems.length} item{sectionItems.length !== 1 ? "s" : ""}
                      </span>
                    </button>
                  </div>

                  {expandedSections[section.key] ? (
                    <div className="border-t border-border/50">
                      {sectionItems.length === 0 ? (
                        <div className="px-5 py-6 text-center text-sm text-muted-foreground">
                          Belum ada item di kategori ini.
                        </div>
                      ) : (
                          <div className="overflow-x-auto pr-4 [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-border [&::-webkit-scrollbar-track]:bg-transparent">
                            <table className="min-w-full border-separate border-spacing-0 text-left text-sm">
                              <thead>
                                <tr className="text-sm text-muted-foreground">
                                  <th className="w-[28%] border-b border-border/70 px-3 py-2 pl-12 font-medium">Nama Item</th>
                                  <th className="w-[60px] border-b border-border/70 px-3 py-2 font-medium text-center">Qty</th>
                                  <th className="w-[70px] border-b border-border/70 px-3 py-2 font-medium">Unit</th>
                                  <th className="w-[18%] border-b border-border/70 px-3 py-2 font-medium text-right">Harga Modal BOQ</th>
                                  <th className="w-[18%] border-b border-border/70 px-3 py-2 font-medium text-right">Plafon Anggaran</th>
                                  <th className="w-[18%] border-b border-border/70 px-3 py-2 font-medium text-right">Subtotal Plafon</th>
                                </tr>
                              </thead>
                            <tbody>
                              {sectionItems.map((item) => (
                                <tr key={item.id} className="transition hover:bg-accent/30">
                                  <td className="border-b border-border/30 px-3 py-3 pl-12 align-top font-medium text-foreground">{item.itemName}</td>
                                  <td className="border-b border-border/30 px-3 py-3 align-top text-center font-medium">{item.quantity}</td>
                                  <td className="border-b border-border/30 px-3 py-3 align-top text-muted-foreground">{item.unit}</td>
                                  <td className="border-b border-border/30 px-3 py-3 align-top text-right font-medium">{formatRupiah(item.unitCostBoq)}</td>
                                  <td className="border-b border-border/30 px-3 py-3 align-top text-right">
                                    <input
                                      value={String(item.plafonAmount)}
                                      onChange={(event) => updatePlafon(item.id, event.target.value)}
                                      className="h-8 w-full min-w-[140px] rounded-lg border border-border/80 bg-background px-2 text-sm text-right outline-none transition focus:border-primary/40 focus:ring-2 focus:ring-primary/10"
                                      disabled={isReadOnly}
                                    />
                                  </td>
                                  <td className="border-b border-border/30 px-3 py-3 align-top text-right font-medium">{formatRupiah(item.plafonAmount)}</td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      )}
                    </div>
                  ) : null}
                </div>
              );
            })}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="space-y-4 p-4 md:p-5">
          <div className={cn("flex items-start gap-3 rounded-xl px-4 py-3 text-sm", diff === 0 ? "bg-emerald-50 text-emerald-800" : "bg-amber-50 text-amber-800")}>
            <CalendarIcon className="mt-0.5 h-4 w-4 shrink-0" />
            <span>
              Total plafon RAP {formatRupiah(summary.totalBudgetModal)} {diff === 0 ? "sesuai" : `berbeda ${formatRupiah(Math.abs(diff))}`} dari total harga modal BOQ Final {formatRupiah(summary.totalBoqCost)}.
            </span>
          </div>

          <div className="flex flex-wrap gap-x-8 gap-y-3 text-sm">
            <div>
              <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Total plafon RAP</p>
              <p className="mt-0.5 text-lg font-bold tracking-tight">{formatRupiah(summary.totalBudgetModal)}</p>
            </div>
            <div>
              <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Total modal BOQ</p>
              <p className="mt-0.5 text-lg font-bold tracking-tight">{formatRupiah(summary.totalBoqCost)}</p>
            </div>
            <div>
              <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Selisih</p>
              <p className="mt-0.5 text-lg font-bold tracking-tight">{diff === 0 ? "Rp 0" : `${diff > 0 ? "+" : "-"}${formatRupiah(Math.abs(diff))}`}</p>
            </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={isReadOnly} className="h-11 px-4">
              Simpan progres
            </Button>
            <Button
              variant="outline"
              onClick={handleSubmit}
              disabled={isReadOnly}
              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>Ajukan RAP ke Operasional</span>
            </Button>
            <Link
              href={status === "locked" ? `/purchase-requests/new?rapId=${workspace.rap.rapId}` : "/purchase-requests"}
              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",
              })}
            >
              <DollarSignIcon className="h-4 w-4" />
              <span>{status === "locked" ? "Buat PR" : "Lihat Purchase Request"}</span>
            </Link>
          </div>

          {status === "pending_operational_review" ? (
            <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 Operasional.</p>
              <p className="mt-1 text-sm text-emerald-900/80">Tahap berikutnya adalah Update RAP oleh Operasional sebelum masuk approval management.</p>
            </div>
          ) : null}
          {status === "pending_approval" ? (
            <div className="rounded-xl bg-sky-50/80 px-4 py-4 text-sm text-sky-900">
              <p className="font-semibold">RAP sudah berada di antrian management approval 3-tier.</p>
              <p className="mt-1 text-sm text-sky-900/80">Approve dari OPS Manager, GA Manager, dan Direktur diperlukan sebelum RAP terkunci.</p>
            </div>
          ) : null}
          {status === "locked" ? (
            <div className="rounded-xl bg-emerald-50/80 px-4 py-4 text-sm text-emerald-900">
              <p className="font-semibold">RAP sudah terkunci.</p>
              <p className="mt-1 text-sm text-emerald-900/80">
                {linkedPurchaseRequest
                  ? `Purchase Request ${linkedPurchaseRequest.prNumber} sudah siap dibuka.`
                  : "Purchase Request sekarang dapat dilanjutkan."}
              </p>
            </div>
          ) : null}
        </CardContent>
      </Card>
    </div>
  );
}
