"use client";

import React, { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import {
  getWarehouses,
  getItems,
  getStockMovementSheets,
  type WarehouseRecord,
  type ItemRecord,
  type StockMovementSheet,
} from "@/lib/api";
import StockMovementSheetModal from "./StockMovementSheetModal";

// ── helpers ───────────────────────────────────────────────────────────────────

function formatNumber(value: number): string {
  return value.toLocaleString('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
}

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

// Export to Excel function
function exportToExcel(sheets: StockMovementSheet[]) {
  // Create CSV content
  const headers = ["Document #", "Report For", "Date", "Total Bags", "Total MT", "Status", "Submitted By", "Created"];
  const rows = sheets.map(s => [
    s.documentNumber ?? `#${s.id.slice(-6).toUpperCase()}`,
    s.stockReportFor ?? s.companyName ?? "—",
    s.documentDate ?? new Date(s.createdAt).toLocaleDateString("en-AE"),
    s.totalBagsAll.toString(),
    s.totalMtAll.toFixed(2),
    s.approvalStatus,
    s.submittedBy ?? "—",
    new Date(s.createdAt).toLocaleDateString("en-AE"),
  ]);

  const csvContent = [
    headers.join(","),
    ...rows.map(row => row.map(cell => `"${cell}"`).join(","))
  ].join("\n");

  // Create blob and download
  const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
  const link = document.createElement("a");
  const url = URL.createObjectURL(blob);
  link.setAttribute("href", url);
  link.setAttribute("download", `stock-movement-sheets-${new Date().toISOString().split('T')[0]}.csv`);
  link.style.visibility = "hidden";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

// ── Main Page ─────────────────────────────────────────────────────────────────

export default function StockInPage() {
  const router = useRouter();
  const [warehouses, setWarehouses] = useState<WarehouseRecord[]>([]);
  const [items, setItems] = useState<ItemRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [sheets, setSheets] = useState<StockMovementSheet[]>([]);
  const [sheetsLoading, setSheetsLoading] = useState(true);

  useEffect(() => {
    Promise.all([getWarehouses(), getItems(), getStockMovementSheets()])
      .then(([wh, it, sh]) => {
        setWarehouses(wh.filter((w) => w.active));
        setItems(it);
        setSheets(sh);
      })
      .catch(() => setError("Failed to load master data."))
      .finally(() => { setLoading(false); setSheetsLoading(false); });
  }, []);

  function onSheetCreated() {
    setSheetsLoading(true);
    getStockMovementSheets()
      .then(setSheets)
      .finally(() => { setSheetsLoading(false); });
  }

  return (
    <>
      <section className="hero">
        <div className="hero-grid">
          <div>
            <h2>Stock In</h2>
            <p>Create a Strategic Stock Movement Sheet. Upload a tax invoice to auto-fill with Royal AI, or fill in manually.</p>
          </div>
          <div style={{ alignSelf: "center" }}>
            <button className="button" onClick={() => setModalOpen(true)}>+ New Sheet</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>
        )}

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

        {!loading && (
          <SheetList sheets={sheets} loading={sheetsLoading} onNew={() => setModalOpen(true)} router={router} />
        )}
      </section>

      {/* Stock Movement Sheet Modal */}
      <StockMovementSheetModal
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        onSuccess={onSheetCreated}
        warehouses={warehouses}
        items={items}
      />
    </>
  );
}

// ── Sheet List ────────────────────────────────────────────────────────────────

function SheetList({ sheets, loading, onNew, router }: {
  sheets: StockMovementSheet[];
  loading: boolean;
  onNew: () => void;
  router: ReturnType<typeof useRouter>;
}) {
  const [currentPage, setCurrentPage] = useState(1);
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const itemsPerPage = 10;

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

  if (loading) return <p style={{ color: "var(--muted)" }}>Loading sheets…</p>;

  if (sheets.length === 0) {
    return (
      <div className="card" style={{ textAlign: "center", padding: 56 }}>
        <p style={{ color: "var(--muted)", margin: "0 0 8px", fontSize: "1rem" }}>No sheets yet.</p>
        <p style={{ color: "var(--muted)", margin: "0 0 24px", fontSize: "0.86rem" }}>
          Create your first Strategic Stock Movement Sheet. Upload a tax invoice to auto-fill with Royal AI.
        </p>
        <button className="button" onClick={onNew}>Create First Sheet</button>
      </div>
    );
  }

  // Filter and search
  const filteredSheets = sheets.filter(s => {
    // Status filter
    if (statusFilter !== "all" && s.approvalStatus !== statusFilter) {
      return false;
    }

    // Search filter
    if (searchQuery.trim() !== "") {
      const query = searchQuery.toLowerCase();
      const matchesDocNumber = s.documentNumber?.toLowerCase().includes(query);
      const matchesReportFor = s.stockReportFor?.toLowerCase().includes(query) || s.companyName?.toLowerCase().includes(query);
      const matchesSubmittedBy = s.submittedBy?.toLowerCase().includes(query);
      const matchesId = s.id.toLowerCase().includes(query);
      
      if (!matchesDocNumber && !matchesReportFor && !matchesSubmittedBy && !matchesId) {
        return false;
      }
    }

    return true;
  });

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

  return (
    <>
      {/* Search and Filter Bar */}
      <div style={{
        display: "flex",
        gap: "12px",
        marginBottom: "18px",
        flexWrap: "wrap",
        alignItems: "center",
        justifyContent: "space-between",
      }}>
        <div style={{ display: "flex", gap: "12px", flex: 1, minWidth: "300px" }}>
          {/* Search Input */}
          <div style={{ position: "relative", flex: 1, maxWidth: "500px" }}>
            <input
              type="text"
              placeholder="Search by document #, company name, or submitted by..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              style={{
                width: "100%",
                padding: "10px 16px 10px 40px",
                borderRadius: "10px",
                border: "1.5px solid var(--line)",
                fontSize: "0.88rem",
                outline: "none",
                transition: "border-color 160ms ease",
              }}
              onFocus={(e) => e.target.style.borderColor = "var(--brand)"}
              onBlur={(e) => e.target.style.borderColor = "var(--line)"}
            />
            <svg
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="var(--muted)"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              style={{
                position: "absolute",
                left: "14px",
                top: "50%",
                transform: "translateY(-50%)",
                pointerEvents: "none",
              }}
            >
              <circle cx="11" cy="11" r="8" />
              <path d="m21 21-4.35-4.35" />
            </svg>
          </div>

          {/* Status Filter */}
          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            style={{
              padding: "10px 16px",
              borderRadius: "10px",
              border: "1.5px solid var(--line)",
              fontSize: "0.88rem",
              fontWeight: 600,
              cursor: "pointer",
              minWidth: "140px",
              maxWidth: "140px",
            }}
          >
            <option value="all">All Status</option>
            <option value="pending_approval">Pending</option>
            <option value="approved">Approved</option>
            <option value="rejected">Rejected</option>
          </select>
        </div>

        {/* Export Button */}
        <button
          onClick={() => exportToExcel(filteredSheets)}
          style={{
            padding: "10px 18px",
            borderRadius: "10px",
            border: "1.5px solid var(--line)",
            background: "#fff",
            color: "var(--ink)",
            fontSize: "0.88rem",
            fontWeight: 600,
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            gap: "8px",
            transition: "all 160ms ease",
            whiteSpace: "nowrap",
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.borderColor = "var(--brand)";
            e.currentTarget.style.color = "var(--brand)";
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.borderColor = "var(--line)";
            e.currentTarget.style.color = "var(--ink)";
          }}
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
            <polyline points="7 10 12 15 17 10" />
            <line x1="12" y1="15" x2="12" y2="3" />
          </svg>
          Export to Excel
        </button>
      </div>

      {/* Results Info */}
      {(searchQuery || statusFilter !== "all") && (
        <div style={{
          marginBottom: "12px",
          padding: "10px 14px",
          background: "#f4f7fd",
          borderRadius: "8px",
          fontSize: "0.84rem",
          color: "var(--muted)",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
        }}>
          <span>
            Showing {filteredSheets.length} of {sheets.length} sheets
            {searchQuery && ` matching "${searchQuery}"`}
            {statusFilter !== "all" && ` with status "${statusFilter.replace('_', ' ')}"`}
          </span>
          {(searchQuery || statusFilter !== "all") && (
            <button
              onClick={() => {
                setSearchQuery("");
                setStatusFilter("all");
              }}
              style={{
                background: "none",
                border: "none",
                color: "var(--brand)",
                fontSize: "0.82rem",
                fontWeight: 600,
                cursor: "pointer",
                padding: "2px 8px",
              }}
            >
              Clear filters
            </button>
          )}
        </div>
      )}

      <div className="card">
        <div className="stock-table-scroll">
          <table className="table stock-table">
            <thead>
              <tr>
                <th>Document #</th>
                <th>Report For</th>
                <th>Date</th>
                <th className="stock-table-num">Total Bags</th>
                <th className="stock-table-num">Total MT</th>
                <th>Status</th>
                <th>Submitted By</th>
                <th>Created</th>
                <th style={{ width: "60px", position: "sticky", right: 0, background: "#f4f7fd", zIndex: 2 }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {currentSheets.length === 0 ? (
                <tr>
                  <td colSpan={9} style={{ textAlign: "center", padding: "40px", color: "var(--muted)" }}>
                    No sheets found matching your filters.
                  </td>
                </tr>
              ) : (
                currentSheets.map((s) => (
                  <tr key={s.id}>
                    <td className="stock-table-nowrap">
                      {s.documentNumber ?? <span style={{ color: "var(--muted)", fontSize: "0.8rem" }}>#{s.id.slice(-6).toUpperCase()}</span>}
                    </td>
                    <td>{s.stockReportFor ?? s.companyName ?? "—"}</td>
                    <td className="stock-table-nowrap">
                      {s.documentDate ?? new Date(s.createdAt).toLocaleDateString("en-AE")}
                    </td>
                    <td className="stock-table-num stock-table-strong">{formatNumber(s.totalBagsAll)}</td>
                    <td className="stock-table-num stock-table-strong stock-table-brand">{formatNumber(s.totalMtAll)}</td>
                    <td>{statusBadge(s.approvalStatus)}</td>
                    <td>{s.submittedBy ?? "—"}</td>
                    <td className="stock-table-nowrap">{new Date(s.createdAt).toLocaleDateString("en-AE")}</td>
                    <td style={{ position: "sticky", right: 0, background: "#fff", padding: "8px", textAlign: "center" }}>
                      <button
                        style={{
                          background: "none",
                          border: "none",
                          cursor: "pointer",
                          color: "var(--brand)",
                          fontSize: "1.1rem",
                          padding: "4px 8px",
                          display: "inline-flex",
                          alignItems: "center",
                          justifyContent: "center",
                        }}
                        onClick={() => router.push(`/stock-movement-sheets/${s.id}`)}
                        title="View details"
                      >
                        <svg
                          width="20"
                          height="20"
                          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>

        {/* Pagination Controls */}
        {totalPages > 1 && (
          <div style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            marginTop: "16px",
            padding: "12px 0",
            borderTop: "1px solid var(--line)",
          }}>
            <div style={{ color: "var(--muted)", fontSize: "0.84rem" }}>
              Showing {startIndex + 1}-{Math.min(endIndex, filteredSheets.length)} of {filteredSheets.length} sheets
            </div>
            <div style={{ display: "flex", gap: "8px" }}>
              <button
                onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                disabled={currentPage === 1}
                style={{
                  padding: "8px 14px",
                  borderRadius: "8px",
                  border: "1px solid var(--line)",
                  background: currentPage === 1 ? "#f4f7fd" : "#fff",
                  color: currentPage === 1 ? "var(--muted)" : "var(--ink)",
                  fontSize: "0.84rem",
                  fontWeight: 600,
                  cursor: currentPage === 1 ? "not-allowed" : "pointer",
                }}
              >
                ← Previous
              </button>
              <div style={{ display: "flex", gap: "4px" }}>
                {Array.from({ length: totalPages }, (_, i) => i + 1).map(page => (
                  <button
                    key={page}
                    onClick={() => setCurrentPage(page)}
                    style={{
                      padding: "8px 12px",
                      borderRadius: "8px",
                      border: "1px solid var(--line)",
                      background: currentPage === page ? "var(--brand)" : "#fff",
                      color: currentPage === page ? "#fff" : "var(--ink)",
                      fontSize: "0.84rem",
                      fontWeight: 600,
                      cursor: "pointer",
                      minWidth: "36px",
                    }}
                  >
                    {page}
                  </button>
                ))}
              </div>
              <button
                onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                disabled={currentPage === totalPages}
                style={{
                  padding: "8px 14px",
                  borderRadius: "8px",
                  border: "1px solid var(--line)",
                  background: currentPage === totalPages ? "#f4f7fd" : "#fff",
                  color: currentPage === totalPages ? "var(--muted)" : "var(--ink)",
                  fontSize: "0.84rem",
                  fontWeight: 600,
                  cursor: currentPage === totalPages ? "not-allowed" : "pointer",
                }}
              >
                Next →
              </button>
            </div>
          </div>
        )}
      </div>
    </>
  );
}
