"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import {
  getStockMovementSheet,
  approveStockMovementSheet,
  rejectStockMovementSheet,
  type StockMovementSheet,
} from "@/lib/api";
import { useAuth } from "@/lib/auth";

function statusBadge(status: string) {
  if (status === "approved") return <span className="badge ok">Approved</span>;
  if (status === "rejected") return <span className="badge danger">Rejected</span>;
  return <span className="badge warn">Pending Approval</span>;
}

export default function StockMovementSheetDetailPage() {
  const { id } = useParams<{ id: string }>();
  const { user } = useAuth();
  const [sheet, setSheet] = useState<StockMovementSheet | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [processing, setProcessing] = useState(false);
  const [rejectReason, setRejectReason] = useState("");
  const [showReject, setShowReject] = useState(false);
  const [showApproveConfirm, setShowApproveConfirm] = useState(false);
  const [showRejectConfirm, setShowRejectConfirm] = useState(false);

  const isManager = user?.role === "store_manager" || user?.role === "super_admin";

  useEffect(() => {
    if (!id) return;
    getStockMovementSheet(id)
      .then(setSheet)
      .catch(() => setError("Failed to load sheet."))
      .finally(() => setLoading(false));
  }, [id]);

  async function handleApprove() {
    if (!id) return;
    setShowApproveConfirm(false);
    setProcessing(true);
    try {
      const updated = await approveStockMovementSheet(id);
      setSheet(updated);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Approval failed.");
    } finally {
      setProcessing(false);
    }
  }

  async function handleReject() {
    if (!id) return;
    setShowRejectConfirm(false);
    setProcessing(true);
    try {
      const updated = await rejectStockMovementSheet(id, rejectReason);
      setSheet(updated);
      setShowReject(false);
      setRejectReason("");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Rejection failed.");
    } finally {
      setProcessing(false);
    }
  }

  if (loading) return <section className="section"><p style={{ color: "var(--muted)" }}>Loading…</p></section>;
  if (!sheet) return <section className="section"><p style={{ color: "var(--danger)" }}>Sheet not found.</p></section>;

  const lineItems = sheet.lineItems ?? [];
  const warehouseNames = Array.from(
    new Set(lineItems.flatMap((li) => Object.keys(li.warehouseBagsNamed ?? li.warehouseBags ?? {})))
  );

  // Table cell styles
  const th: React.CSSProperties = {
    padding: "12px 14px",
    textAlign: "left",
    color: "var(--muted)",
    fontSize: "0.78rem",
    textTransform: "uppercase",
    letterSpacing: "0.06em",
    whiteSpace: "nowrap",
    borderBottom: "2px solid var(--line)",
    borderRight: "1px solid var(--line)",
    background: "#f4f7fd",
    fontWeight: 700,
  };
  const thNum: React.CSSProperties = { ...th, textAlign: "right", color: "var(--brand)" };
  const thWh: React.CSSProperties = { ...th, textAlign: "right", color: "var(--brand)", minWidth: 110 };
  const td: React.CSSProperties = {
    padding: "11px 14px",
    borderBottom: "1px solid var(--line)",
    borderRight: "1px solid var(--line)",
    fontSize: "0.9rem",
    color: "var(--ink)",
    whiteSpace: "nowrap",
  };
  const tdNum: React.CSSProperties = { ...td, textAlign: "right" };
  const tdMuted: React.CSSProperties = { ...td, color: "var(--muted)" };

  return (
    <>
      <section className="hero">
        <div className="hero-grid">
          <div>
            <h2>Strategic Stock Movement Sheet</h2>
            <p style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
              {statusBadge(sheet.approvalStatus)}
              {sheet.submittedBy && (
                <span style={{ color: "rgba(255, 255, 255, 0.7)", fontSize: "0.86rem" }}>
                  Submitted by <strong style={{ color: "#ffffff" }}>{sheet.submittedBy}</strong>
                </span>
              )}
              {sheet.approvedBy && (
                <span style={{ color: "rgba(255, 255, 255, 0.7)", fontSize: "0.86rem" }}>
                  · Approved by <strong style={{ color: "#ffffff" }}>{sheet.approvedBy}</strong>
                </span>
              )}
            </p>
          </div>
          {isManager && sheet.approvalStatus === "pending_approval" && (
            <div style={{ display: "flex", gap: 10, alignSelf: "center" }}>
              <button className="button" disabled={processing} onClick={() => setShowApproveConfirm(true)}>
                {processing ? "…" : "Approve"}
              </button>
              <button
                className="button secondary"
                style={{ color: "var(--danger)", borderColor: "var(--danger)" }}
                disabled={processing}
                onClick={() => setShowRejectConfirm(true)}
              >
                Reject
              </button>
            </div>
          )}
        </div>
      </section>

      <section className="section">
        {error && (
          <div className="snackbar snackbar-error" style={{ marginBottom: 18 }}>
            {error}
            <button className="snackbar-close" onClick={() => setError(null)}>✕</button>
          </div>
        )}

        {/* Slim summary bar — only the 4 fields that matter */}
        <div style={{
          display: "flex", gap: 0, marginBottom: 20,
          background: "#fff", border: "1px solid var(--line)",
          borderRadius: 10, overflow: "hidden",
        }}>
          {[
            { label: "Submitted By", value: sheet.submittedBy ?? "—" },
            { label: "Approved By", value: sheet.approvedBy ?? "—" },
            { label: "Total Bags", value: sheet.totalBagsAll.toLocaleString(), highlight: false },
            { label: "Total MT", value: sheet.totalMtAll.toFixed(2) + " MT", highlight: true },
          ].map(({ label, value, highlight }, i, arr) => (
            <div key={label} style={{
              flex: 1, padding: "16px 20px",
              borderRight: i < arr.length - 1 ? "1px solid var(--line)" : "none",
            }}>
              <p style={{ margin: 0, fontSize: "0.72rem", textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--muted)", fontWeight: 600 }}>{label}</p>
              <p style={{ margin: "4px 0 0", fontSize: "1.1rem", fontWeight: 700, color: highlight ? "var(--brand)" : "var(--ink)" }}>{value}</p>
            </div>
          ))}
        </div>

        {/* Approval / rejection banner */}
        {sheet.approvalStatus === "approved" && (
          <div className="card" style={{ marginBottom: 18, background: "var(--brand-soft)", border: "1px solid rgba(59,91,219,0.2)" }}>
            <p style={{ margin: 0, color: "var(--brand)", fontSize: "0.9rem" }}>
              ✓ Approved by <strong>{sheet.approvedBy}</strong>
              {sheet.approvedAt && <> on {new Date(sheet.approvedAt).toLocaleString("en-AE")}</>}
            </p>
          </div>
        )}
        {sheet.approvalStatus === "rejected" && (
          <div className="card" style={{ marginBottom: 18, background: "#fff5f5", border: "1px solid rgba(214,69,69,0.2)" }}>
            <p style={{ margin: 0, color: "var(--danger)", fontSize: "0.9rem" }}>
              ✕ Rejected by <strong>{sheet.rejectedBy}</strong> — {sheet.rejectedReason || "No reason provided"}
            </p>
          </div>
        )}

        {/* Line items table */}
        {lineItems.length > 0 && (
          <div className="card" style={{ padding: 0, overflow: "hidden" }}>
            <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <strong style={{ fontSize: "0.96rem" }}>Line Items</strong>
              <span style={{ color: "var(--muted)", fontSize: "0.84rem" }}>{lineItems.length} row{lineItems.length !== 1 ? "s" : ""}</span>
            </div>
            <div style={{ overflowX: "auto" }}>
              <table style={{ borderCollapse: "collapse", width: "100%", minWidth: `${700 + warehouseNames.length * 120}px` }}>
                <thead>
                  <tr>
                    <th style={{ ...th, minWidth: 40 }}>#</th>
                    <th style={{ ...th, minWidth: 130 }}>Item Code</th>
                    <th style={{ ...th, minWidth: 240 }}>Item Name</th>
                    <th style={{ ...th, minWidth: 120 }}>Batch</th>
                    <th style={{ ...th, minWidth: 110 }}>Expiry</th>
                    <th style={{ ...th, minWidth: 80 }}>Unit</th>
                    {warehouseNames.map((wn) => (
                      <th key={wn} style={thWh}>{wn}</th>
                    ))}
                    <th style={{ ...thNum, minWidth: 110 }}>Total Bags</th>
                    <th style={{ ...thNum, minWidth: 100, borderRight: "none" }}>Total MT</th>
                  </tr>
                </thead>
                <tbody>
                  {lineItems.map((li, idx) => {
                    const bags = li.warehouseBagsNamed ?? li.warehouseBags ?? {};
                    const isEven = idx % 2 === 0;
                    return (
                      <tr key={li.lineNumber} style={{ background: isEven ? "#fff" : "#fafbff" }}>
                        <td style={tdMuted}>{li.lineNumber}</td>
                        <td style={{ ...td, fontFamily: "monospace", fontSize: "0.84rem" }}>{li.itemCode ?? "—"}</td>
                        <td style={{ ...td, fontWeight: 600, maxWidth: 280, overflow: "hidden", textOverflow: "ellipsis" }}>{li.itemName ?? "—"}</td>
                        <td style={td}>{li.batchNumber || "—"}</td>
                        <td style={tdMuted}>{li.expiryDate || "—"}</td>
                        <td style={tdMuted}>{li.unit ?? "—"}</td>
                        {warehouseNames.map((wn) => (
                          <td key={wn} style={{ ...tdNum, color: (bags[wn] ?? 0) > 0 ? "var(--ink)" : "var(--muted)", fontWeight: (bags[wn] ?? 0) > 0 ? 600 : 400 }}>
                            {(bags[wn] ?? 0) > 0 ? (bags[wn] as number).toLocaleString() : "—"}
                          </td>
                        ))}
                        <td style={{ ...tdNum, fontWeight: 700 }}>{li.totalBags.toLocaleString()}</td>
                        <td style={{ ...tdNum, fontWeight: 700, color: "var(--brand)", borderRight: "none" }}>{li.totalMt.toFixed(2)}</td>
                      </tr>
                    );
                  })}
                  {/* Grand total row */}
                  <tr style={{ background: "#f4f7fd", borderTop: "2px solid var(--line)" }}>
                    <td colSpan={6 + warehouseNames.length} style={{ ...td, fontWeight: 700, fontSize: "0.9rem", background: "#f4f7fd" }}>
                      GRAND TOTAL
                    </td>
                    <td style={{ ...tdNum, fontWeight: 800, fontSize: "1rem", background: "#f4f7fd" }}>
                      {sheet.totalBagsAll.toLocaleString()}
                    </td>
                    <td style={{ ...tdNum, fontWeight: 800, fontSize: "1rem", color: "var(--brand)", background: "#f4f7fd", borderRight: "none" }}>
                      {sheet.totalMtAll.toFixed(2)}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        )}
      </section>

      {/* Approve Confirmation Modal */}
      {showApproveConfirm && (
        <div className="doc-modal-backdrop" onClick={() => setShowApproveConfirm(false)}>
          <div className="doc-modal" style={{ maxWidth: 420 }} onClick={(e) => e.stopPropagation()}>
            <div className="doc-modal-header">
              <div>
                <strong className="doc-modal-title">Confirm Approval</strong>
                <span className="doc-modal-meta">Are you sure you want to approve this sheet?</span>
              </div>
              <button className="doc-modal-close" onClick={() => setShowApproveConfirm(false)}>✕</button>
            </div>
            <div className="doc-modal-body" style={{ padding: 22 }}>
              <p style={{ margin: "0 0 18px", color: "var(--muted)", fontSize: "0.88rem" }}>
                This action will approve the stock movement sheet and update inventory balances accordingly.
              </p>
              <div style={{ display: "flex", gap: 10 }}>
                <button className="button" disabled={processing} onClick={handleApprove} style={{ flex: 1 }}>
                  {processing ? "Approving…" : "Yes, Approve"}
                </button>
                <button className="button secondary" onClick={() => setShowApproveConfirm(false)} style={{ flex: 1 }}>
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Reject Confirmation Modal */}
      {showRejectConfirm && (
        <div className="doc-modal-backdrop" onClick={() => setShowRejectConfirm(false)}>
          <div className="doc-modal" style={{ maxWidth: 420 }} onClick={(e) => e.stopPropagation()}>
            <div className="doc-modal-header">
              <div>
                <strong className="doc-modal-title">Confirm Rejection</strong>
                <span className="doc-modal-meta">Are you sure you want to reject this sheet?</span>
              </div>
              <button className="doc-modal-close" onClick={() => setShowRejectConfirm(false)}>✕</button>
            </div>
            <div className="doc-modal-body" style={{ padding: 22 }}>
              <p style={{ margin: "0 0 18px", color: "var(--muted)", fontSize: "0.88rem" }}>
                You will be asked to provide a reason for rejection in the next step.
              </p>
              <div style={{ display: "flex", gap: 10 }}>
                <button 
                  className="button" 
                  style={{ background: "var(--danger)", flex: 1 }} 
                  onClick={() => {
                    setShowRejectConfirm(false);
                    setShowReject(true);
                  }}
                >
                  Yes, Reject
                </button>
                <button className="button secondary" onClick={() => setShowRejectConfirm(false)} style={{ flex: 1 }}>
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Reject modal */}
      {showReject && (
        <div className="doc-modal-backdrop" onClick={() => setShowReject(false)}>
          <div className="doc-modal" style={{ maxWidth: 480 }} onClick={(e) => e.stopPropagation()}>
            <div className="doc-modal-header">
              <div>
                <strong className="doc-modal-title">Reject Sheet</strong>
                <span className="doc-modal-meta">Provide a reason for rejection</span>
              </div>
              <button className="doc-modal-close" onClick={() => setShowReject(false)}>✕</button>
            </div>
            <div className="doc-modal-body" style={{ padding: 22 }}>
              <div className="form-field">
                <label className="form-label">Reason <span className="form-optional">optional</span></label>
                <textarea className="form-input" value={rejectReason} onChange={(e) => setRejectReason(e.target.value)} placeholder="Enter rejection reason…" rows={3} />
              </div>
              <div style={{ display: "flex", gap: 10, marginTop: 16 }}>
                <button className="button" style={{ background: "var(--danger)" }} disabled={processing} onClick={handleReject}>
                  {processing ? "Rejecting…" : "Confirm Reject"}
                </button>
                <button className="button secondary" onClick={() => setShowReject(false)}>Cancel</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
