﻿import React, { useEffect, useState } from "react";
import {
  Button,
  Card,
  Typography,
  Table,
  Input,
  Pagination,
  Popconfirm,
  Tag,
  Tooltip,
  Modal,
  Select,
} from "antd";
import {
  Plus,
  Search,
  Trash2,
  Building,
  Mail,
  Phone,
  CheckCircle,
  XCircle,
  Info,
  Users,
  UsersRound,
} from "lucide-react";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import toast from "react-hot-toast";
import { useDebounce } from "@/hooks/useDebounce";
import dayjs from "dayjs";
import { ColumnsType } from "antd/es/table";

const { Text } = Typography;

interface IInstitution {
  id: string;
  firstName?: string;
  lastName?: string;
  institutionName?: string;
  institutionAddress?: string;
  contactPerson?: string;
  email: string;
  phone?: string;
  role: string;
  isVerified: boolean;
  createdAt: string;
  studentCount?: number;
  staffCount?: number;
}

const paginationInitial = {
  page: 1,
  limit: 10,
  total: 0,
  totalPages: 0,
};

const Institutions: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<IInstitution[]>([]);
  const [pagination, setPagination] = useState(paginationInitial);
  const [search, setSearch] = useState("");
  const [isVerified, setIsVerified] = useState<string | undefined>(undefined);
  const debouncedSearch = useDebounce(search, 500);

  const fetchInstitutions = async (
    page = 1,
    limit = 10,
    search = "",
    isVerified?: string,
  ) => {
    setLoading(true);
    try {
      const res = await API_Instance.get(API_Constants.users, {
        params: {
          page,
          limit,
          role: "Institution",
          search,
          isVerified,
        },
      });
      setData(res.data.data);
      setPagination(res.data.meta);
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchInstitutions(1, pagination.limit, debouncedSearch, isVerified);
  }, [debouncedSearch, isVerified]);


  const columns: ColumnsType<IInstitution> = [
    {
      title: "Institution Name",
      dataIndex: "institutionName",
      key: "institutionName",
      render: (text, record) => (
        <div className="flex flex-col">
          <span className="font-semibold text-slate-700">
            {text || record.firstName}
          </span>
          <span className="text-xs text-slate-500">
            {record.institutionAddress}
          </span>
        </div>
      ),
    },
    {
      title: "Contact Person",
      key: "contact",
      render: (_, record) => (
        <div className="flex flex-col text-sm text-slate-600">
          <span className="font-medium">{record.contactPerson}</span>
        </div>
      ),
    },
    {
      title: "Email & Phone",
      key: "emailPhone",
      render: (_, record) => (
        <div className="flex flex-col gap-1 text-sm text-slate-600">
          <div className="flex items-center gap-1">
            <Mail size={14} className="text-slate-400" />
            <span className="text-md">{record.email}</span>
          </div>
          {record.phone && (
            <div className="flex items-center gap-1">
              <Phone size={14} className="text-slate-400" />
              <span className="text-sm">{record.phone}</span>
            </div>
          )}
        </div>
      ),
    },
    {
      title: "Capacity",
      key: "capacity",
      render: (_, record) => (
        <div className="flex gap-2">
          <div className="flex items-center gap-2">
            <span className="p-1.5 rounded-lg bg-blue-50 text-blue-600">
              <Users size={14} />
            </span>
            <div className="flex flex-col">
              <span className="text-sm font-bold text-slate-700">
                {record.studentCount || 0}
              </span>
              <span className="text-[10px] uppercase tracking-wider font-bold text-slate-400">
                Students
              </span>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <span className="p-1.5 rounded-lg bg-emerald-50 text-emerald-600">
              <UsersRound size={14} />
            </span>
            <div className="flex flex-col">
              <span className="text-sm font-bold text-slate-700">
                {record.staffCount || 0}
              </span>
              <span className="text-[10px] uppercase tracking-wider font-bold text-slate-400">
                Staff
              </span>
            </div>
          </div>
        </div>
      ),
    },
    {
      title: "Status",
      dataIndex: "isVerified",
      key: "isVerified",
      render: (verified) => (
        <Tag
          color={verified ? "success" : "warning"}
          className="flex w-fit items-center gap-1"
        >
          {verified ? <CheckCircle size={12} /> : <XCircle size={12} />}
          {verified ? "Verified" : "Pending"}
        </Tag>
      ),
    },
    {
      title: "Joined Date",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (date) => (
        <span className="text-xs text-slate-500">
          {dayjs(date).format("DD MMM YYYY, hh:mm A")}
        </span>
      ),
    },
    // {
    //   title: "Action",
    //   key: "action",
    //   align: "center",
    //   width: 100,
    //   render: (_, record) => (
    //     <div className="flex justify-center gap-2">
    //       {/* <Tooltip title="Edit">
    //         <Button
    //           type="text"
    //           className="text-blue-500 hover:text-blue-700 hover:bg-blue-50"
    //           icon={<Edit size={16} />}
    //           // onClick={() => handleEdit(record)} // Implement edit if needed
    //         />
    //       </Tooltip> */}
    //       <Popconfirm
    //         title="Delete Institution"
    //         description="Are you sure you want to delete this institution? This action cannot be undone."
    //         onConfirm={() => handleDelete(record.id)}
    //         okText="Yes"
    //         cancelText="No"
    //         okButtonProps={{ danger: true }}
    //       >
    //         <Button
    //           type="text"
    //           danger
    //           className="hover:bg-red-50"
    //           icon={<Trash2 size={16} />}
    //         />
    //       </Popconfirm>
    //     </div>
    //   ),
    // },
  ];

  return (
    <div className="flex flex-col gap-4 px-4 py-6">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h2 className="text-2xl font-bold text-slate-800 flex items-center gap-2">
            <Building className="text-blue-600" /> Institutions Management
          </h2>
          <p className="text-slate-500 text-sm mt-1">
            Manage registered institutions and their details.
          </p>
        </div>

        {/* <Button type="primary" icon={<Plus size={16} />} onClick={() => {}}>
            Add Institution
        </Button> */}
      </div>

      <Card className="shadow-sm border border-slate-200 rounded-xl">
        <div className="flex justify-between items-center mb-4">
          <div className="flex flex-wrap items-center gap-4 mb-4">
            <div className="w-full md:w-72">
              <Input
                placeholder="Search institution, email..."
                prefix={<Search size={16} className="text-slate-400" />}
                allowClear
                value={search}
                onChange={(e) => setSearch(e.target.value)}
              />
            </div>

            <Select
              placeholder="Verified Status"
              className="w-full md:w-40"
              allowClear
              value={isVerified}
              onChange={(val) => setIsVerified(val)}
              options={[
                { label: "Verified", value: "true" },
                { label: "Pending", value: "false" },
              ]}
            />

            <Button
              type="link"
              size="small"
              className="text-slate-500 hover:text-blue-600 p-0 h-auto"
              onClick={() => {
                setSearch("");
                setIsVerified(undefined);
              }}
            >
              Clear All
            </Button>

            <div className="ml-auto text-slate-500 text-sm">
              Total:{" "}
              <span className="font-semibold text-slate-800">
                {pagination.total}
              </span>
            </div>
          </div>
        </div>

        <Table
          columns={columns}
          dataSource={data}
          loading={loading}
          rowKey="id"
          pagination={false}
          scroll={{ x: 800 }}
          className="border border-slate-100 rounded-lg overflow-hidden"
        />

        <div className="flex justify-end mt-4">
          <Pagination
            current={pagination.page}
            total={pagination.total}
            pageSize={pagination.limit}
            onChange={(page, pageSize) => {
              setPagination((prev) => ({ ...prev, page, limit: pageSize }));
              fetchInstitutions(page, pageSize, debouncedSearch);
            }}
            showSizeChanger
            showTotal={(total) => `Total ${total} items`}
          />
        </div>
      </Card>
    </div>
  );
};

export default Institutions;
