"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import {
  getWarehouses,
  getAllTransactions,
  type WarehouseRecord,
  type StockTransaction,
} from "@/lib/api";
import StockOutModal from "./StockOutModal";

export default function StockOutPage() {
  const router = useRouter();
  const [warehouses, setWarehouses] = useState<WarehouseRecord[]>([]);
  const [sheets, setSheets] = useState<StockTransaction[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);

  // Search and filter
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");

  // Pagination
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 10;

  useEffect(() => {
    loadData();
  }, [statusFilter]); // Reload when status filter changes

  async function loadData() {
    setLoading(true);
    try {
      const [wh, transactions] = await Promise.all([
        getWarehouses(),
        getAllTransactions({ status: statusFilter }),
      ]);
      setWarehouses(wh.filter((w) => w.active));
      // Filter only outbound transactions
      const outboundTransactions = transactions.filter((t) => t.type === "outbound");
      console.log("All transactions:", transactions.length);
      console.log("Outbound transactions:", outboundTransactions.length);
      console.log("Sample transaction:", outboundTransactions[0]);
      setSheets(outboundTransactions);
    } catch (error) {
      console.error("Failed to load data:", error);
    } finally {
      setLoading(false);
    }
  }

  function handleModalSuccess() {
    setShowModal(false);
    loadData();
  }

  // Apply search filter only (status filtering is done by API)
  const filteredSheets = sheets.filter((sheet) => {
    // Search filter
    const searchLower = searchQuery.toLowerCase();
    const matchesSearch =
      !searchQuery ||
      sheet.id.toLowerCase().includes(searchLower) ||
      sheet.itemCode?.toLowerCase().includes(searchLower) ||
      sheet.itemName?.toLowerCase().includes(searchLower) ||
      sheet.warehouseName?.toLowerCase().includes(searchLower) ||
      sheet.batchNumber?.toLowerCase().includes(searchLower) ||
      sheet.submittedBy?.toLowerCase().includes(searchLower);

    return matchesSearch;
  });

  // Pagination
  const totalPages = Math.ceil(filteredSheets.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const currentSheets = filteredSheets.slice(startIndex, endIndex);

  // Reset to page 1 when filters change
  useEffect(() => {
    setCurrentPage(1);
  }, [searchQuery, statusFilter]);

  // Export to CSV
  function handleExport() {
    const headers = [
      "Transaction ID",
      "Date",
      "Warehouse",
      "Item Code",
      "Item Name",
      "Batch Number",
      "Expiry Date",
      "Quantity (MT)",
      "Status",
      "Submitted By",
    ];

    const rows = filteredSheets.map((sheet) => [
      sheet.id,
      new Date(sheet.createdAt).toLocaleDateString("en-AE"),
      sheet.warehouseName ?? "—",
      sheet.itemCode ?? "—",
      sheet.itemName ?? "—",
      sheet.batchNumber ?? "—",
      sheet.expiryDate ? new Date(sheet.expiryDate).toLocaleDateString("en-AE") : "—",
      sheet.quantityMt.toString(),
      sheet.approvalStatus,
      sheet.submittedBy ?? "—",
    ]);

    const csvContent = [headers, ...rows].map((row) => row.join(",")).join("\n");
    const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `stock-out-transactions-${new Date().toISOString().split("T")[0]}.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  }

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

  const hasActiveFilters = searchQuery || statusFilter !== "all";

  return (
    <>
      <section className="hero">
        <div className="hero-grid">
          <div>
            <h2>Stock Out</h2>
            <p>Create stock-out transactions and track approval status</p>
          </div>
          <div style={{ alignSelf: "center" }}>
            <button
              className="button"
              onClick={() => setShowModal(true)}
              style={{ display: "flex", alignItems: "center", gap: 8 }}
            >
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2.5"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <line x1="12" y1="5" x2="12" y2="19" />
                <line x1="5" y1="12" x2="19" y2="12" />
              </svg>
              New Stock Out
            </button>
          </div>
        </div>
      </section>

      <section className="section">
        {/* Filter Bar */}
        <div className="section-header" style={{ flexWrap: "wrap", gap: 12 }}>
          <div>
            <h3>Stock-Out Transactions</h3>
            <p>
              {filteredSheets.length} transaction{filteredSheets.length !== 1 ? "s" : ""}
            </p>
          </div>

          <div className="filters" style={{ flexWrap: "wrap" }}>
            {/* Search */}
            <input
              type="text"
              placeholder="Search by transaction ID, item code, warehouse, or submitted by..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              style={{
                padding: "8px 14px",
                borderRadius: 8,
                border: "1.5px solid var(--line)",
                fontSize: "0.82rem",
                outline: "none",
                minWidth: 500,
                maxWidth: 500,
              }}
            />

            {/* Status Filter */}
            <div className="select-wrapper" style={{ minWidth: 140, maxWidth: 140 }}>
              <select
                className="premium-select"
                style={{ padding: "8px 36px 8px 12px", fontSize: "0.82rem" }}
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
              >
                <option value="all">All Status</option>
                <option value="pending_approval">Pending</option>
                <option value="approved">Approved</option>
                <option value="rejected">Rejected</option>
              </select>
              <span className="select-chevron">▾</span>
            </div>

            {/* Clear Filters */}
            {hasActiveFilters && (
              <button
                className="button secondary"
                style={{ padding: "8px 14px", fontSize: "0.78rem" }}
                onClick={() => {
                  setSearchQuery("");
                  setStatusFilter("all");
                }}
              >
                Clear filters
              </button>
            )}

            {/* Export */}
            <button
              className="button secondary"
              style={{ padding: "8px 14px", fontSize: "0.78rem" }}
              onClick={handleExport}
              disabled={filteredSheets.length === 0}
            >
              Export to Excel
            </button>
          </div>
        </div>

        {/* Filter Results Info */}
        {hasActiveFilters && (
          <div
            style={{
              marginBottom: 16,
              padding: "10px 14px",
              background: "#f0f4ff",
              border: "1px solid rgba(59,91,219,0.2)",
              borderRadius: 8,
              fontSize: "0.84rem",
              color: "var(--brand)",
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
            }}
          >
            <span>
              Showing {filteredSheets.length} transaction{filteredSheets.length !== 1 ? "s" : ""}
              {searchQuery && ` matching "${searchQuery}"`}
              {statusFilter !== "all" && ` with status "${statusFilter}"`}
            </span>
            <button
              onClick={() => {
                setSearchQuery("");
                setStatusFilter("all");
              }}
              style={{
                background: "none",
                border: "none",
                color: "var(--brand)",
                cursor: "pointer",
                fontSize: "0.82rem",
                fontWeight: 600,
                textDecoration: "underline",
              }}
            >
              Clear filters
            </button>
          </div>
        )}

        {loading && <p style={{ color: "var(--muted)" }}>Loading…</p>}

        {!loading && sheets.length === 0 && (
          <div className="empty-preview">
            <p style={{ marginBottom: 16 }}>No stock-out transactions yet.</p>
            <button className="button" onClick={() => setShowModal(true)}>
              Create First Stock-Out
            </button>
          </div>
        )}

        {!loading && sheets.length > 0 && filteredSheets.length === 0 && (
          <div className="empty-preview">
            <p>No transactions match your filters.</p>
            <button
              className="button secondary"
              onClick={() => {
                setSearchQuery("");
                setStatusFilter("all");
              }}
            >
              Clear Filters
            </button>
          </div>
        )}

        {!loading && currentSheets.length > 0 && (
          <>
            {/* Table */}
            <div className="card" style={{ padding: 0, overflow: "hidden" }}>
              <div style={{ overflowX: "auto" }}>
                <table style={{ borderCollapse: "collapse", width: "100%", minWidth: "1000px" }}>
                  <thead>
                    <tr>
                      <th
                        style={{
                          padding: "12px 14px",
                          textAlign: "left",
                          color: "var(--muted)",
                          fontSize: "0.75rem",
                          textTransform: "uppercase",
                          letterSpacing: "0.06em",
                          whiteSpace: "nowrap",
                          borderBottom: "2px solid var(--line)",
                          background: "#f4f7fd",
                          fontWeight: 700,
                        }}
                      >
                        Transaction ID
                      </th>
                      <th
                        style={{
                          padding: "12px 14px",
                          textAlign: "left",
                          color: "var(--muted)",
                          fontSize: "0.75rem",
                          textTransform: "uppercase",
                          letterSpacing: "0.06em",
                          whiteSpace: "nowrap",
                          borderBottom: "2px solid var(--line)",
                          background: "#f4f7fd",
                          fontWeight: 700,
                        }}
                      >
                        Date
                      </th>
                      <th
                        style={{
                          padding: "12px 14px",
                          textAlign: "left",
                          color: "var(--muted)",
                          fontSize: "0.75rem",
                          textTransform: "uppercase",
                          letterSpacing: "0.06em",
                          whiteSpace: "nowrap",
                          borderBottom: "2px solid var(--line)",
                          background: "#f4f7fd",
                          fontWeight: 700,
                        }}
                      >
                        Warehouse
                      </th>
                      <th
                        style={{
                          padding: "12px 14px",
                          textAlign: "left",
                          color: "var(--muted)",
                          fontSize: "0.75rem",
                          textTransform: "uppercase",
                          letterSpacing: "0.06em",
                          whiteSpace: "nowrap",
                          borderBottom: "2px solid var(--line)",
                          background: "#f4f7fd",
                          fontWeight: 700,
                        }}
                      >
                        Item Code
                      </th>
                      <th
                        style={{
                          padding: "12px 14px",
                          textAlign: "left",
                          color: "var(--muted)",
                          fontSize: "0.75rem",
                          textTransform: "uppercase",
                          letterSpacing: "0.06em",
                          whiteSpace: "nowrap",
                          borderBottom: "2px solid var(--line)",
                          background: "#f4f7fd",
                          fontWeight: 700,
                        }}
                      >
                        Batch Number
                      </th>
                      <th
                        style={{
                          padding: "12px 14px",
                          textAlign: "left",
                          color: "var(--muted)",
                          fontSize: "0.75rem",
                          textTransform: "uppercase",
                          letterSpacing: "0.06em",
                          whiteSpace: "nowrap",
                          borderBottom: "2px solid var(--line)",
                          background: "#f4f7fd",
                          fontWeight: 700,
                        }}
                      >
                        Expiry Date
                      </th>
                      <th
                        style={{
                          padding: "12px 14px",
                          textAlign: "right",
                          color: "var(--muted)",
                          fontSize: "0.75rem",
                          textTransform: "uppercase",
                          letterSpacing: "0.06em",
                          whiteSpace: "nowrap",
                          borderBottom: "2px solid var(--line)",
                          background: "#f4f7fd",
                          fontWeight: 700,
                        }}
                      >
                        Total MT
                      </th>
                      <th
                        style={{
                          padding: "12px 14px",
                          textAlign: "left",
                          color: "var(--muted)",
                          fontSize: "0.75rem",
                          textTransform: "uppercase",
                          letterSpacing: "0.06em",
                          whiteSpace: "nowrap",
                          borderBottom: "2px solid var(--line)",
                          background: "#f4f7fd",
                          fontWeight: 700,
                        }}
                      >
                        Status
                      </th>
                      <th
                        style={{
                          padding: "12px 14px",
                          textAlign: "left",
                          color: "var(--muted)",
                          fontSize: "0.75rem",
                          textTransform: "uppercase",
                          letterSpacing: "0.06em",
                          whiteSpace: "nowrap",
                          borderBottom: "2px solid var(--line)",
                          background: "#f4f7fd",
                          fontWeight: 700,
                        }}
                      >
                        Submitted By
                      </th>
                      <th
                        style={{
                          padding: "12px 14px",
                          textAlign: "center",
                          color: "var(--muted)",
                          fontSize: "0.75rem",
                          textTransform: "uppercase",
                          letterSpacing: "0.06em",
                          whiteSpace: "nowrap",
                          borderBottom: "2px solid var(--line)",
                          background: "#f4f7fd",
                          fontWeight: 700,
                          position: "sticky",
                          right: 0,
                          zIndex: 2,
                        }}
                      >
                        Actions
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {currentSheets.map((sheet, idx) => {
                      const isEven = idx % 2 === 0;
                      return (
                        <tr
                          key={sheet.id}
                          style={{
                            background: isEven ? "#fff" : "#fafbff",
                            borderBottom: "1px solid var(--line)",
                          }}
                        >
                          <td
                            style={{
                              padding: "11px 14px",
                              fontSize: "0.84rem",
                              fontFamily: "monospace",
                              color: "var(--ink)",
                            }}
                          >
                            {sheet.id.slice(0, 8)}...
                          </td>
                          <td style={{ padding: "11px 14px", fontSize: "0.84rem", color: "var(--muted)" }}>
                            {new Date(sheet.createdAt).toLocaleDateString("en-AE")}
                          </td>
                          <td style={{ padding: "11px 14px", fontSize: "0.84rem", color: "var(--ink)" }}>
                            {sheet.warehouseName ?? "—"}
                          </td>
                          <td
                            style={{
                              padding: "11px 14px",
                              fontSize: "0.84rem",
                              fontFamily: "monospace",
                              color: "var(--ink)",
                              fontWeight: 600,
                            }}
                          >
                            {sheet.itemCode ?? "—"}
                          </td>
                          <td style={{ padding: "11px 14px", fontSize: "0.84rem", color: "var(--muted)" }}>
                            {sheet.batchNumber ?? "—"}
                          </td>
                          <td style={{ padding: "11px 14px", fontSize: "0.84rem", color: "var(--ink)" }}>
                            {sheet.expiryDate 
                              ? new Date(sheet.expiryDate).toLocaleDateString("en-AE")
                              : "—"
                            }
                          </td>
                          <td
                            style={{
                              padding: "11px 14px",
                              fontSize: "0.84rem",
                              color: "var(--brand)",
                              fontWeight: 700,
                              textAlign: "right",
                            }}
                          >
                            {sheet.quantityMt.toFixed(2)}
                          </td>
                          <td style={{ padding: "11px 14px" }}>{statusBadge(sheet.approvalStatus)}</td>
                          <td style={{ padding: "11px 14px", fontSize: "0.84rem", color: "var(--muted)" }}>
                            {sheet.submittedBy ?? "—"}
                          </td>
                          <td
                            style={{
                              padding: "11px 14px",
                              textAlign: "center",
                              position: "sticky",
                              right: 0,
                              background: isEven ? "#fff" : "#fafbff",
                              zIndex: 2,
                            }}
                          >
                            <button
                              onClick={() => router.push(`/approvals`)}
                              style={{
                                background: "none",
                                border: "none",
                                cursor: "pointer",
                                color: "var(--brand)",
                                padding: "4px 8px",
                              }}
                              title="View details"
                            >
                              <svg
                                width="18"
                                height="18"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="2"
                                strokeLinecap="round"
                                strokeLinejoin="round"
                              >
                                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
                                <circle cx="12" cy="12" r="3" />
                              </svg>
                            </button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
              <div
                style={{
                  marginTop: 20,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                  flexWrap: "wrap",
                  gap: 12,
                }}
              >
                <p style={{ margin: 0, fontSize: "0.84rem", color: "var(--muted)" }}>
                  Showing {startIndex + 1}-{Math.min(endIndex, filteredSheets.length)} of{" "}
                  {filteredSheets.length} transactions
                </p>

                <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                  <button
                    onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                    disabled={currentPage === 1}
                    style={{
                      padding: "6px 12px",
                      borderRadius: 6,
                      border: "1.5px solid var(--line)",
                      background: currentPage === 1 ? "#f8f9fb" : "#fff",
                      color: currentPage === 1 ? "var(--muted)" : "var(--ink)",
                      fontSize: "0.82rem",
                      fontWeight: 600,
                      cursor: currentPage === 1 ? "not-allowed" : "pointer",
                    }}
                  >
                    Previous
                  </button>

                  {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
                    <button
                      key={page}
                      onClick={() => setCurrentPage(page)}
                      style={{
                        padding: "6px 12px",
                        borderRadius: 6,
                        border: `1.5px solid ${page === currentPage ? "var(--brand)" : "var(--line)"}`,
                        background: page === currentPage ? "var(--brand)" : "#fff",
                        color: page === currentPage ? "#fff" : "var(--ink)",
                        fontSize: "0.82rem",
                        fontWeight: 600,
                        cursor: "pointer",
                        minWidth: 36,
                      }}
                    >
                      {page}
                    </button>
                  ))}

                  <button
                    onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                    disabled={currentPage === totalPages}
                    style={{
                      padding: "6px 12px",
                      borderRadius: 6,
                      border: "1.5px solid var(--line)",
                      background: currentPage === totalPages ? "#f8f9fb" : "#fff",
                      color: currentPage === totalPages ? "var(--muted)" : "var(--ink)",
                      fontSize: "0.82rem",
                      fontWeight: 600,
                      cursor: currentPage === totalPages ? "not-allowed" : "pointer",
                    }}
                  >
                    Next
                  </button>
                </div>
              </div>
            )}
          </>
        )}
      </section>

      {/* Stock-Out Modal */}
      <StockOutModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        onSuccess={handleModalSuccess}
        warehouses={warehouses}
      />
    </>
  );
}
