"use client";

import React, { useEffect, useMemo, useState } from "react";
import toast from "react-hot-toast";
import { FiSearch, FiRefreshCw, FiMapPin, FiPhone, FiMail } from "react-icons/fi";
import { clientPortalApi } from "@/lib/api/clientPortalApi";
import styles from "../../../(dashboard)/modules/commonstyle/dattabale.module.css";

interface Branch {
  id: number;
  name?: string;
  location?: string;
  address?: string;
  phone?: string;
  email?: string;
  contact_person?: string;
  designation?: string;
}

function extractArray(res: any): any[] {
  if (Array.isArray(res)) return res;
  if (Array.isArray(res?.data)) return res.data;
  if (Array.isArray(res?.data?.data)) return res.data.data;
  return [];
}

function getPageNumbers(current: number, total: number): (number | "...")[] {
  if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);
  const pages: (number | "...")[] = [1];
  if (current > 3) pages.push("...");
  for (let p = Math.max(2, current - 1); p <= Math.min(total - 1, current + 1); p++) {
    pages.push(p);
  }
  if (current < total - 2) pages.push("...");
  pages.push(total);
  return pages;
}

export default function BranchesPage() {
  const [branches, setBranches] = useState<Branch[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [rowsPerPage, setRowsPerPage] = useState(10);

  useEffect(() => {
    fetchBranches();
  }, []);

  const fetchBranches = async () => {
    try {
      setLoading(true);
      const response = await clientPortalApi.getBranches();
      setBranches(extractArray(response));
    } catch (error) {
      toast.error("Failed to load branches");
    } finally {
      setLoading(false);
    }
  };

  const filtered = useMemo(() => {
    const term = searchTerm.toLowerCase();
    return branches.filter(
      (b) => !term || b.name?.toLowerCase().includes(term) || b.location?.toLowerCase().includes(term)
    );
  }, [branches, searchTerm]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / rowsPerPage));
  const paginated = filtered.slice((currentPage - 1) * rowsPerPage, currentPage * rowsPerPage);

  const isHeadOffice = (b: Branch) =>
    (b.name || "").toLowerCase().includes("head office") || (b.location || "").toLowerCase().includes("head office");

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <h1 className={styles.title}>Company branches</h1>
          <p className={styles.subtitle}>
            Locations and contact information
            {branches.length > 0 ? " \u00b7 " + branches.length + " total" : ""}
          </p>
        </div>
        <div className={styles.headerRight}>
          <button className={styles.btnSecondary} onClick={fetchBranches}>
            <FiRefreshCw className={styles.icon} /> Refresh
          </button>
        </div>
      </div>

      <div className={styles.statsBar}>
        <div className={styles.stat}>
          <span className={styles.statLabel}>Total branches</span>
          <span className={styles.statValue}>{branches.length}</span>
        </div>
      </div>

      <div className={styles.toolbar}>
        <div className={styles.toolbarTop}>
          <div className={styles.searchBox}>
            <span className={styles.searchIcon}>
              <FiSearch />
            </span>
            <input
              type="text"
              className={styles.searchInput}
              placeholder="Search branches..."
              value={searchTerm}
              onChange={(e) => {
                setSearchTerm(e.target.value);
                setCurrentPage(1);
              }}
            />
          </div>
        </div>
      </div>

      {loading ? (
        <div className={styles.errorContainer}>
          <p className={styles.errorMessage}>Loading branches...</p>
        </div>
      ) : paginated.length === 0 ? (
        <div className={styles.emptyState}>
          <span>No branches found</span>
        </div>
      ) : (
        <>
          <div className={styles.tableWrapper}>
            <table className={styles.table}>
              <thead>
                <tr>
                  <th className={styles.th}>Branch</th>
                  <th className={styles.th}>Address</th>
                  <th className={styles.th}>Contact</th>
                  <th className={styles.th}>Contact person</th>
                </tr>
              </thead>
              <tbody>
                {paginated.map((branch) => (
                  <tr key={branch.id}>
                    <td>
                      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <div
                          style={{
                            width: 32,
                            height: 32,
                            borderRadius: 8,
                            background: "#fffbeb",
                            color: "#d97706",
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "center",
                            flexShrink: 0,
                          }}
                        >
                          <FiMapPin size={15} />
                        </div>
                        <div>
                          <div className={styles.nameCell}>{branch.name || "Branch"}</div>
                          <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 2 }}>
                            <span style={{ fontSize: 11, color: "#94a3b8" }}>{branch.location || "\u2014"}</span>
                            {isHeadOffice(branch) && (
                              <span style={{ background: "#eef2ff", color: "#4338ca", fontSize: 10, fontWeight: 700, padding: "1px 7px", borderRadius: 99 }}>
                                Head office
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                    </td>
                    <td style={{ maxWidth: 280 }}>{branch.address || "\u2014"}</td>
                    <td>
                      <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                        {branch.phone && (
                          <a
                            href={"tel:" + branch.phone}
                            style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12, color: "#0f766e", textDecoration: "none" }}
                          >
                            <FiPhone size={11} /> {branch.phone}
                          </a>
                        )}
                        {branch.email && (
                          <a
                            href={"mailto:" + branch.email}
                            style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12, color: "#4338ca", textDecoration: "none" }}
                          >
                            <FiMail size={11} /> {branch.email}
                          </a>
                        )}
                        {!branch.phone && !branch.email && "\u2014"}
                      </div>
                    </td>
                    <td>
                      {branch.contact_person || "\u2014"}
                      {branch.designation ? " \u00b7 " + branch.designation : ""}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div className={styles.pagination}>
            <div className={styles.paginationLeft}>
              <span className={styles.paginationText}>
                Showing <strong>{(currentPage - 1) * rowsPerPage + 1}</strong>&ndash;
                <strong>{Math.min(currentPage * rowsPerPage, filtered.length)}</strong> of{" "}
                <strong>{filtered.length}</strong>
              </span>
            </div>
            <div className={styles.paginationRight}>
              <button className={styles.pageBtn} disabled={currentPage === 1} onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}>
                &lsaquo;
              </button>
              {getPageNumbers(currentPage, totalPages).map((p, idx) =>
                p === "..." ? (
                  <span key={"ellipsis-" + idx} className={styles.pageEllipsis}>&middot;&middot;&middot;</span>
                ) : (
                  <button key={p} className={p === currentPage ? styles.activePageBtn : styles.pageBtn} onClick={() => setCurrentPage(p)}>
                    {p}
                  </button>
                )
              )}
              <button className={styles.pageBtn} disabled={currentPage === totalPages} onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}>
                &rsaquo;
              </button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}