/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */

import { useState, useMemo } from "react";

import AdminLayout from "@/layouts/admin-layout";

import DashStatsCard from "@/components/shared/DashStatsCard";

import NewDataTable, {
  Action,
  Column,
} from "@/components/shared/NewDataTable";

import Pagination from "@/components/dashboard/pagination";

import MemberSearch from "@/components/members/member-search";

import DashboardHeader from "@/components/shared/DashPageHeader";

import PageIntro from "@/components/dashboard/page-intro";

import styles from "./pastors.module.scss";

import { router } from "@inertiajs/react";

import CreatePastorModal from "@/components/modals/create-pastor-modal";

import AssignHeadPastorModal from "@/components/modals/assign-head-pastor-to-branch";

import TransferPastorModal from "@/components/modals/transfer-pastor-modal";
import { clipEmail } from "@/lib/utils";

import {
  FiUsers,
  FiUserCheck,
  FiUserX,
  FiSend,
} from "react-icons/fi";

import {
  PieChart,
  Pie,
  Cell,
  Legend,
  Tooltip,
  ResponsiveContainer,
} from "recharts";

/* =========================================================
| TYPES
* ========================================================= */

type Pastor = {
  id: string;
  name: string;
  email: string;
  phone: string;
  station: string;
  state: string;
  status: "Active" | "Inactive";
  age: number;
  gender: "Male" | "Female";
  degree: string;
  maritalStatus: string;
};

/* =========================================================
| COLORS
* ========================================================= */

const COLORS_DISTINCT = [
  "#FF6384",
  "#36A2EB",
  "#FFCE56",
  "#4BC0C0",
  "#9966FF",
  "#FF9F40",
  "#00A36C",
  "#E83E8C",
  "#17A2B8",
];

/* =========================================================
| PAGE
* ========================================================= */

const AdminPastors = ({
  pastors: paginatedPastors,
  allPastors,
  branches,
  statistics,
}: any) => {
  /* =========================================================
  | STATE
  * ========================================================= */
  const [searchTerm, setSearchTerm] = useState("");

  const [createModal, setCreateModal] = useState(false);

  const [showAssignModal, setShowAssignModal] = useState(false);

  const [transferModal, setTransferModal] = useState(false);

  const [chartType, setChartType] = useState<
    "age" |
    "gender" |
    "degree" |
    "status" |
    "marital" |
    "state"
  >("age");

  const [viewType, setViewType] = useState<
    "count" | "percentage"
  >("count");

  /* =========================================================
  | TOGGLES
  * ========================================================= */

  const toggleHeadPastorModal = () => {
    setShowAssignModal((prev) => !prev);
  };

  const toggleCreateModal = () => {
    setCreateModal((prev) => !prev);
  };

  /* =========================================================
  | TABLE DATA (PAGINATED)
  * ========================================================= */

  const pastors: Pastor[] = useMemo(() => {

    if (!paginatedPastors?.data) return [];

    return paginatedPastors.data.map((p: any) => {

      const age =
        p.date_of_birth
          ? new Date().getFullYear() -
            new Date(p.date_of_birth).getFullYear()
          : 0;

      return {

        id: p.id,

        name: `${p.first_name} ${p.last_name}`,

        email: clipEmail(p.email),

        phone: p.phone,

        station: p.branch?.name ?? "Unassigned",

        state: p.state,

        age,

        gender: p.gender,

        degree:
          p.qualification ?? "N/A",

        maritalStatus:
          p.marital_status ?? "N/A",
      };
    });

  }, [paginatedPastors]);

  /* =========================================================
  | ANALYTICS DATA (ALL RECORDS)
  * ========================================================= */

  const analyticsPastors: Pastor[] = useMemo(() => {

    if (!allPastors) return [];

    return allPastors.map((p: any) => {

      const age =
        p.date_of_birth
          ? new Date().getFullYear() -
            new Date(p.date_of_birth).getFullYear()
          : 0;

      return {

        id: p.id,

        name: `${p.first_name} ${p.last_name} ${p.surname ?? ""}`,

        email: p.email,

        phone: p.phone,

        station: p.branch?.name ?? "Unassigned",

        state: p.state,

        status: p.is_suspended
          ? "Inactive"
          : "Active",

        age,

        gender: p.gender,

        degree:
          p.qualification ?? "N/A",

        maritalStatus:
          p.marital_status ?? "N/A",
      };
    });

  }, [allPastors]);

  /* =========================================================
  | FILTERED TABLE DATA
  * ========================================================= */

  const filteredData = useMemo(() => {

    return pastors.filter((item) =>
      item.name
        .toLowerCase()
        .includes(searchTerm.toLowerCase()) ||

      item.email
        .toLowerCase()
        .includes(searchTerm.toLowerCase())
    );

  }, [searchTerm, pastors]);

  /* =========================================================
  | TABLE COLUMNS
  * ========================================================= */

  const columns: Column<Pastor>[] = [

    {
      header: "Name",
      accessor: "name",
    },

    {
      header: "Email",
      accessor: "email",
    },

    {
      header: "Phone Number",
      accessor: "phone",
    },

    {
      header: "Station",
      accessor: "station",
    },
  ];

  /* =========================================================
  | ACTIONS
  * ========================================================= */

  const actions: Action<Pastor>[] = [

    {
      label: "See Details",

      onClick: (r) =>
        router.visit(`/admin/pastors/${r.id}`),
    },

    // {
    //   label: "Update",

    //   onClick: (r) =>
    //     router.visit(`/admin/pastors/${r.id}/edit`),

    //   variant: "update",
    // },

    // {
    //   label: "Delete",

    //   onClick: (r) =>
    //     router.delete(`/admin/pastors/${r.id}`),

    //   variant: "delete",
    // },
  ];

  /* =========================================================
  | STATS
  * ========================================================= */

  const stats = [

    {
      title: "Total Pastors",

      value: Number(
        statistics.total || 0
      ).toLocaleString(),

      icon: <FiUsers />,
    },

    {
      title: "Active Pastors",

      value: Number(
        statistics.active || 0
      ).toLocaleString(),

      icon: <FiUserCheck />,

      positive: true,
    },

    {
      title: "Suspended Pastors",

      value: Number(
        statistics.suspended || 0
      ).toLocaleString(),

      icon: <FiUserX />,

      positive: false,
    },

    {
      title: "Assigned To Branch",

      value: Number(
        statistics.assigned_to_branch || 0
      ).toLocaleString(),

      icon: <FiUsers />,
    },
  ];

  /* =========================================================
  | CHART DATA (ALL RECORDS)
  * ========================================================= */

  const chartData = useMemo(() => {

    const group: Record<string, number> = {};

    analyticsPastors.forEach((p) => {

      let key = "";

      switch (chartType) {

        case "age":

          key =
            p.age < 30
              ? "20-29"
              : p.age < 40
              ? "30-39"
              : p.age < 50
              ? "40-49"
              : "50+";

          break;

        case "gender":

          key = p.gender;

          break;

        case "degree":

          key = p.degree;

          break;

        case "status":

          key = p.status;

          break;

        case "marital":

          key = p.maritalStatus;

          break;

        case "state":

          key = p.state;

          break;
      }

      group[key] = (group[key] || 0) + 1;
    });

    const total = analyticsPastors.length;

    return Object.entries(group).map(
      ([name, value]) => ({

        name,

        value:
          viewType === "percentage"
            ? Number(
                ((value / total) * 100).toFixed(1)
              )
            : value,
      })
    );

  }, [
    chartType,
    viewType,
    analyticsPastors,
  ]);

  /* =========================================================
  | RENDER
  * ========================================================= */


  return (
    <>
      {/* =========================================================
      | CREATE MODAL
      * ========================================================= */}

      {createModal && (

        <CreatePastorModal
          branches={branches}
          closeModal={toggleCreateModal}
        />
      )}

      {/* =========================================================
      | ASSIGN HEAD PASTOR MODAL
      * ========================================================= */}

      {showAssignModal && (

        <AssignHeadPastorModal
          branches={branches}
          pastors={allPastors}
          closeModal={toggleHeadPastorModal}
        />
      )}


      {transferModal && (

        <TransferPastorModal
          branches={branches}
          pastors={allPastors}
          closeModal={() => setTransferModal(!transferModal)}
        />
      )}

      {/* =========================================================
      | PAGE
      * ========================================================= */}

      <div className={styles.page}>

        <DashboardHeader
          title="Manage Pastors"
          description="View & manage all pastors across branches from one dashboard"
          // actionButton={{
          //   label: "Add New Pastor",
          //   onClick: toggleCreateModal,
          // }}
        />

        <div className={styles.content}>

          {/* =========================================================
          | STATS
          * ========================================================= */}

          <h2 className={styles.statsTitle}>
            Pastor's Statistics
          </h2>

          <p className={styles.statsDesc}>
            Overview of pastor's statistics
          </p>

          <DashStatsCard stats={stats} />

          <br />
          <br />

          {/* =========================================================
          | CHART
          * ========================================================= */}

          <h2 className={styles.statsTitle}>
            Distribution Data
          </h2>

          <p className={styles.statsDesc}>
            Overview of the data distributions
            of Censers pastors
          </p>

          <div className={styles.chartSection}>

            {/* CHART TABS */}

            <div className={styles.chartTabs}>

              {[
                "Age",
                "Gender",
                "Degree",
                "Status",
                "Marital",
                "State",
              ].map((type) => (

                <button
                  key={type}
                  className={
                    chartType ===
                    type.toLowerCase().replace(" ", "")
                      ? styles.activeChart
                      : ""
                  }
                  onClick={() =>
                    setChartType(
                      type
                        .toLowerCase()
                        .replace(" ", "") as any
                    )
                  }
                >
                  {type}
                </button>
              ))}
            </div>

            {/* VIEW TABS */}

            <div className={styles.viewTabs}>

              <button
                className={
                  viewType === "count"
                    ? styles.activeView
                    : ""
                }
                onClick={() =>
                  setViewType("count")
                }
              >
                Count
              </button>

              <button
                className={
                  viewType === "percentage"
                    ? styles.activeView
                    : ""
                }
                onClick={() =>
                  setViewType("percentage")
                }
              >
                Percentage
              </button>
            </div>

            {/* PIE CHART */}

            <ResponsiveContainer
              width="100%"
              height={300}
            >

              <PieChart>

                <Pie
                  data={chartData}
                  dataKey="value"
                  nameKey="name"
                  outerRadius={100}
                  label={(entry: any) =>

                    viewType === "percentage"

                      ? `${entry.name}: ${entry.value}%`

                      : `${entry.name}: ${entry.value}`
                  }
                >

                  {chartData.map((_, index) => (

                    <Cell
                      key={index}
                      fill={
                        COLORS_DISTINCT[
                          index % COLORS_DISTINCT.length
                        ]
                      }
                    />
                  ))}
                </Pie>

                <Tooltip />

                <Legend />

              </PieChart>

            </ResponsiveContainer>
          </div>

          <br />

          {/* =========================================================
          | QUICK ACTIONS
          * ========================================================= */}

          <div className={styles.quickActions}>

            <PageIntro
              title="Quick Actions"
              description="Perform quick administrative actions on pastors"
            />

            <div className={styles.actionsOptions}>

              {/* TRANSFER */}

              <div className={styles.actionCard} onClick={() => setTransferModal(!transferModal)}>

                <div className={styles.actionLeft}>
                  <span>
                    <FiSend />
                  </span>
                </div>

                <div className={styles.actionContent}>
                  <h1>Transfer Pastor</h1>
                  <p>
                    Move pastor to another branch
                  </p>
                </div>
              </div>

              {/* ASSIGN HEAD PASTOR */}

              <div
                className={styles.actionCard}
                onClick={toggleHeadPastorModal}
              >

                <div className={styles.actionLeft}>
                  <span>
                    <FiUserCheck />
                  </span>
                </div>

                <div className={styles.actionContent}>
                  <h1>
                    Assign Head Pastor To A Branch
                  </h1>

                  <p>
                    Grant access and send invite
                    link to become a head pastor
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* =========================================================
          | TABLE
          * ========================================================= */}

          <div className={styles.topBar}>

            <div className={styles.search}>

              <MemberSearch
                placeholder="Search by name or email..."
                url=""
              />
            </div>
          </div>

          <div className={styles.tableCard}>

            <div className={styles.tableWrapper}>

              <NewDataTable<Pastor>
                data={filteredData}
                columns={columns}
                actions={actions}
              />
            </div>

            <Pagination
              links={paginatedPastors.links}
              onChange={() => {}}
            />
          </div>
        </div>
      </div>
    </>
  );
};

AdminPastors.layout = (page: any) => (
  <AdminLayout title="Manage Pastors">
    {page}
  </AdminLayout>
);

export default AdminPastors;

