/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState, useMemo } from "react";
import DashboardLayout from "@/layouts/dashboard";
import DashStatsCard from "@/components/shared/DashStatsCard";
import DataTable, { Action, Column } from "@/components/shared/DataTable";
import Pagination from "@/components/dashboard/pagination";
import Search from "@/components/shared/search";
import styles from "./pastors.module.scss";
import {
  FiUsers,
  FiUserCheck,
  FiUserX,
  FiUserMinus,
  FiPlus,
  FiSend,
  FiRepeat,
  FiSlash,
} from "react-icons/fi";
import { PieChart, Pie, Cell, Legend, Tooltip, ResponsiveContainer } from "recharts";

type Pastor = {
  id: string;
  name: string;
  email: string;
  phone: string;
  station: string;
  status: "Active" | "Inactive";
  age: number;
  gender: "Male" | "Female";
  degree: "WAEC" | "First Degree" | "Masters Degree" | "Ph.D";
  maritalStatus: "Single" | "Married" | "Divorced" | "Widowed";
};

// Distinct chart colors
const COLORS_DISTINCT = [
  "#FF6384", "#36A2EB", "#FFCE56", "#4BC0C0", "#9966FF",
  "#FF9F40", "#00A36C", "#E83E8C", "#17A2B8", "#FFC0CB",
  "#8B0000", "#00FF7F"
];

const DashboardPastors = () => {
  const [activeTab, setActiveTab] = useState<"pastors" | "ministers">("pastors");
  const [searchTerm, setSearchTerm] = useState("");
  const [showModal, setShowModal] = useState(false);
  const [chartType, setChartType] = useState<"age" | "gender" | "degree" | "status" | "marital">("age");

  // ================= SAMPLE DATA =================
  const pastors: Pastor[] = Array.from({ length: 12 }, (_, i) => ({
    id: `P-${i + 1}`,
    name: `Pastor John ${i + 1}`,
    email: `pastor${i + 1}@church.com`,
    phone: `+234 80${i} 000 000${i}`,
    station: `Branch ${i + 1}`,
    status: i % 3 === 0 ? "Inactive" : "Active",
    age: 25 + i * 3,
    gender: i % 2 === 0 ? "Male" : "Female",
    degree: ["WAEC", "First Degree", "Masters Degree", "Ph.D"][i % 4] as Pastor["degree"],
    maritalStatus: ["Single", "Married", "Divorced", "Widowed"][i % 4] as Pastor["maritalStatus"],
  }));

  const ministers: Pastor[] = Array.from({ length: 10 }, (_, i) => ({
    id: `M-${i + 1}`,
    name: `Minister Grace ${i + 1}`,
    email: `minister${i + 1}@church.com`,
    phone: `+234 81${i} 111 111${i}`,
    station: `Branch ${i + 3}`,
    status: i % 4 === 0 ? "Inactive" : "Active",
    age: 28 + i * 2,
    gender: i % 2 === 0 ? "Female" : "Male",
    degree: ["WAEC", "First Degree", "Masters Degree", "Ph.D"][i % 4] as Pastor["degree"],
    maritalStatus: ["Single", "Married", "Divorced", "Widowed"][i % 4] as Pastor["maritalStatus"],
  }));

  const rawData = activeTab === "pastors" ? pastors : ministers;

  const filteredData = useMemo(
    () =>
      rawData.filter(
        (item) =>
          item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
          item.email.toLowerCase().includes(searchTerm.toLowerCase())
      ),
    [searchTerm, rawData]
  );

  // ================= TABLE =================
  const columns: Column<Pastor>[] = [
    { header: "Name", accessor: "name" },
    { header: "Email", accessor: "email" },
    { header: "Phone", accessor: "phone" },
    { header: "Station", accessor: "station" },
    { header: "Status", accessor: "status" },
  ];

  const actions: Action<Pastor>[] = [
    { label: "View", onClick: (r) => window.location.href = `/dashboard/pastors/${r.id}` },
    { label: "Update", onClick: (r) => alert(r.id), variant: "update" },
    { label: "Delete", onClick: (r) => alert(r.id), variant: "delete" },
  ];

  // ================= STATS =================
  const stats = [
    { title: "Total Pastors", value: 120, icon: <FiUsers /> },
    { title: "Total Ministers", value: 85, icon: <FiUsers /> },
    { title: "Active Pastors", value: 100, icon: <FiUserCheck />, positive: true },
    { title: "Suspended Pastors", value: 20, icon: <FiUserX />, positive: false },
    { title: "Active Ministers", value: 70, icon: <FiUserCheck />, positive: true },
    { title: "Suspended Ministers", value: 15, icon: <FiUserMinus />, positive: false },
  ];

  // ================= PIE CHART DATA =================
  const chartData = useMemo(() => {
    const data: { name: string; value: number }[] = [];
    switch (chartType) {
      case "age": {
        const ageGroups: Record<string, number> = { "20-29": 0, "30-39": 0, "40-49": 0, "50+": 0 };
        rawData.forEach(p => {
          if (p.age < 30) ageGroups["20-29"]++;
          else if (p.age < 40) ageGroups["30-39"]++;
          else if (p.age < 50) ageGroups["40-49"]++;
          else ageGroups["50+"]++;
        });
        Object.entries(ageGroups).forEach(([name, value]) => data.push({ name, value }));
        break;
      }
      case "gender": {
        const genderGroups: Record<string, number> = { Male: 0, Female: 0 };
        rawData.forEach(p => genderGroups[p.gender]++);
        Object.entries(genderGroups).forEach(([name, value]) => data.push({ name, value }));
        break;
      }
      case "degree": {
        const degreeGroups: Record<string, number> = { WAEC: 0, "First Degree": 0, "Masters Degree": 0, "Ph.D": 0 };
        rawData.forEach(p => degreeGroups[p.degree]++);
        Object.entries(degreeGroups).forEach(([name, value]) => data.push({ name, value }));
        break;
      }
      case "status": {
        const statusGroups: Record<string, number> = { Active: 0, Inactive: 0 };
        rawData.forEach(p => statusGroups[p.status]++);
        Object.entries(statusGroups).forEach(([name, value]) => data.push({ name, value }));
        break;
      }
      case "marital": {
        const maritalGroups: Record<string, number> = { Single: 0, Married: 0, Divorced: 0, Widowed: 0 };
        rawData.forEach(p => maritalGroups[p.maritalStatus]++);
        Object.entries(maritalGroups).forEach(([name, value]) => data.push({ name, value }));
        break;
      }
    }
    return data;
  }, [chartType, rawData]);

  return (
    <div className={styles.page}>
      {/* ================= HERO HEADER ================= */}
      <div className={styles.hero}>
        <div className={styles.heroOverlay}></div>
        <div className={styles.heroContent}>
          <div className={styles.heroText}>
            <h1>Pastors & Ministers</h1>
            <p>Enterprise leadership management across all branches with clarity and control.</p>
          </div>

          <div className={styles.heroButtons}>
            <button className={styles.primary}><FiPlus /> Add Pastor</button>
            <button className={styles.secondary}><FiPlus /> Add Minister</button>
            <button className={styles.ghost}><FiSend /> Send Message</button>
            <button className={styles.ghost}><FiRepeat /> Transfer</button>
            <button className={styles.danger} onClick={() => setShowModal(true)}><FiSlash /> Suspend</button>
          </div>
        </div>
      </div>

      <div className={styles.content}>
        <h2 className={styles.statsTitle}>Pastor's Statistics</h2>
        <p className={styles.statsDesc}>Overview of pastor's statistics</p>
        <DashStatsCard stats={stats} /><br />

        {/* ================= PIE 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}>
          <div className={styles.chartTabs}>
            {["age", "gender", "degree", "status", "marital"].map(type => (
              <button
                key={type}
                className={chartType === type ? styles.activeChart : ""}
                onClick={() => setChartType(type as any)}
              >
                {type.charAt(0).toUpperCase() + type.slice(1)}
              </button>
            ))}
          </div>
          
          <ResponsiveContainer width="100%" height={300}>
            <PieChart>
              <Pie
                data={chartData}
                dataKey="value"
                nameKey="name"
                outerRadius={100}
                label={({ name, percent }) =>
                  `${name}: ${percent !== undefined ? (percent * 100).toFixed(0) : 0}%`
                }
                isAnimationActive={true}
              >
                {chartData.map((_, index) => (
                  <Cell key={index} fill={COLORS_DISTINCT[index % COLORS_DISTINCT.length]} />
                ))}
              </Pie>
              <Tooltip formatter={(value?: number, name?: string) => [`${value ?? 0}`, name ?? ""]} />
              <Legend />
            </PieChart>
          </ResponsiveContainer>
        </div>

        {/* ================= TOP BAR ================= */}
        <div className={styles.topBar}>
          <div className={styles.tabs}>
            <button className={activeTab === "pastors" ? styles.active : ""} onClick={() => setActiveTab("pastors")}>Pastors</button>
            <button className={activeTab === "ministers" ? styles.active : ""} onClick={() => setActiveTab("ministers")}>Ministers</button>
            <div className={`${styles.indicator} ${activeTab === "ministers" ? styles.move : ""}`} />
          </div>

          <div className={styles.search}>
            <Search placeholder="Search by name or email..." url="" />
          </div>
        </div>

        {/* ================= TABLE CARD ================= */}
        <div className={styles.tableCard}>
          <DataTable<Pastor> data={filteredData} columns={columns} actions={actions} />

          <Pagination
            links={[
              { url: null, label: "«", active: false },
              { url: "#", label: "1", active: true },
              { url: "#", label: "2", active: false },
              { url: "#", label: "»", active: false },
            ]}
            onChange={() => {}}
          />
        </div>

        {/* ================= MODAL ================= */}
        {showModal && (
          <div className={styles.modalOverlay}>
            <div className={styles.modal}>
              <h3>Suspend Account</h3>
              <p>Are you sure you want to suspend this leadership account?</p>
              <div className={styles.modalActions}>
                <button className={styles.cancel} onClick={() => setShowModal(false)}>Cancel</button>
                <button className={styles.confirm}>Confirm Suspend</button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

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

export default DashboardPastors;
