import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { getCustomersByInsurance } from "../../API";
import Swal from "sweetalert2";
import { DataTable } from "mantine-datatable";
import {
  FaBuilding,
  FaEnvelope,
  FaPhone,
  FaUsers,
  FaMapMarkerAlt,
  FaGlobe,
  FaUser,
  FaVenus,
  FaMars,
  FaTransgender,
} from "react-icons/fa";
import { useLoader } from "../../store/LoaderProvider";

interface Customer {
  cust_id: string;
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  gender: string;
  birthdate: string;
  address: string;
  city: string;
  state: string;
  country: string;
  zip: string;
}

interface CompanyDetails {
  insurance_name: string;
  total_customers: number;
}

const ViewInsuranceCustomer = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  const [loading, setLoading] = useState(false);
  const [company, setCompany] = useState<CompanyDetails | null>(null);
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [error, setError] = useState<string | null>(null);
  
  // DataTable states
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [sortStatus, setSortStatus] = useState({
    columnAccessor: "firstName",
    direction: "asc" as "asc" | "desc",
  });
     const { showLoader, hideLoader } = useLoader();

  const PAGE_SIZES = [5, 10, 15, 20, 50];

  useEffect(() => {
    const fetchCustomers = async () => {
      showLoader();
      try {
        const response = await getCustomersByInsurance(id);
        if (response.status === "success") {
          setCompany({
            insurance_name: response.insurance_name,
            total_customers: response.total_customers,
          });
          setCustomers(response.data || []);
        } else {
          throw new Error(response.message || "Failed to fetch data");
        }
      } catch (err: any) {
        setError(err.message);
        Swal.fire({
          title: "Error!",
          text: err.message || "Failed to load data",
          icon: "error",
          confirmButtonColor: "#A8916A",
        }).then(() => navigate("/insurance"));
      } finally {
        hideLoader();
      }
    };

    fetchCustomers();
  }, [id, navigate]);

  // Get gender icon
  const getGenderIcon = (gender: string) => {
    switch (gender?.toLowerCase()) {
      case "male":
        return <FaMars className="text-blue-500" />;
      case "female":
        return <FaVenus className="text-pink-500" />;
      default:
        return <FaTransgender className="text-purple-500" />;
    }
  };

  // Format birthdate
  const formatBirthdate = (dateString: string) => {
    if (!dateString) return "N/A";
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString();
    } catch {
      return dateString;
    }
  };

  const recordsData = customers.slice(
    (page - 1) * pageSize,
    page * pageSize
  );

  return (
    <div className="mx-auto p-4">
      {loading && (
        <div className="fixed inset-0 flex justify-center items-center bg-black bg-opacity-50 z-[9999]">
          <div className="w-16 h-16 border-t-4 border-primary-DEFAULT border-solid rounded-full animate-spin"></div>
        </div>
      )}

      {!loading && error && (
        <div className="p-4 mb-6 bg-red-100 text-red-600 rounded-lg">{error}</div>
      )}

      {!loading && company && (
        <div className="bg-white dark:bg-gray-900 rounded-lg shadow-md border border-gray-200 dark:border-gray-700 p-6">
          {/* 🔹 Company Details Section */}
          <h2 className="text-2xl font-semibold text-secondary dark:text-white mb-4 border-b border-primary-light pb-2">
            Insurance Company Details
          </h2>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div className="flex items-center space-x-2 bg-gray-50 dark:bg-gray-800 p-2 rounded-md border border-gray-200 dark:border-gray-700">
              <FaBuilding className="text-primary" />
              <span className="text-secondary dark:text-white font-medium">
                {company.insurance_name}
              </span>
            </div>

            <div className="flex items-center space-x-2 bg-gray-50 dark:bg-gray-800 p-2 rounded-md border border-gray-200 dark:border-gray-700">
              <FaUsers className="text-primary" />
              <span className="text-secondary dark:text-white font-medium">
                Total Customers: {company.total_customers}
              </span>
            </div>
          </div>

          {/* 🔹 Customer List Section */}
          <h3 className="text-xl font-semibold text-secondary dark:text-white mb-3 border-b border-primary-light pb-2 flex items-center gap-2">
            <FaUsers className="text-primary" />
            Customers
          </h3>

          {customers.length === 0 ? (
            <p className="text-gray-600 dark:text-gray-400 text-center py-6">
              No customers found for this insurance.
            </p>
          ) : (
            <div className="datatables">
              <DataTable
                highlightOnHover
                className="whitespace-nowrap table-hover rounded-lg overflow-hidden"
                records={recordsData}
                columns={[
                  {
                    accessor: "index",
                    title: "Sr No.",
                    width: 80,
                    render: (record, index) => (
                      <span className="text-gray-600 dark:text-gray-300">
                        {(page - 1) * pageSize + index + 1}
                      </span>
                    ),
                  },
                  {
                    accessor: "name",
                    title: "Name",
                    sortable: true,
                    render: ({ firstName, lastName, gender }) => (
                      <div className="flex items-center gap-3">
                        {/* <div className="w-10 h-10 rounded-full bg-primary/10 dark:bg-primary-dark-light flex items-center justify-center">
                          <FaUser className="text-primary-DEFAULT dark:text-primary-light text-lg" />
                        </div> */}
                        <div>
                          <div className="font-medium text-secondary dark:text-white">
                            {firstName} {lastName}
                          </div>
                          <div className="flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400">
                            {getGenderIcon(gender)}
                            <span className="capitalize">{gender || "N/A"}</span>
                          </div>
                        </div>
                      </div>
                    ),
                  },
                  {
                    accessor: "email",
                    title: "Email",
                    sortable: true,
                    render: ({ email }) => (
                      <div className="flex items-center gap-2 text-gray-600 dark:text-gray-300">
                        <FaEnvelope className="text-gray-400 flex-shrink-0" />
                        <span className="truncate">{email || "N/A"}</span>
                      </div>
                    ),
                  },
                  {
                    accessor: "phone",
                    title: "Phone",
                    sortable: true,
                    render: ({ phone }) => (
                      <div className="flex items-center gap-2 text-gray-600 dark:text-gray-300">
                        <FaPhone className="text-gray-400 flex-shrink-0" />
                        <span>{phone || "N/A"}</span>
                      </div>
                    ),
                  },
                  {
                    accessor: "address",
                    title: "Address",
                    sortable: true,
                    render: ({ address, city, state, country, zip }) => (
                      <div className="flex items-start gap-2 text-gray-600 dark:text-gray-300">
                        <FaMapMarkerAlt className="text-gray-400 flex-shrink-0 mt-1" />
                        <div className="text-sm">
                          <div>{address || "N/A"}</div>
                          <div className="text-xs text-gray-500 dark:text-gray-400">
                            {city && state ? `${city}, ${state}` : "N/A"}
                            {zip && ` - ${zip}`}
                          </div>
                          {country && (
                            <div className="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1">
                              <FaGlobe className="text-xs" />
                              {country}
                            </div>
                          )}
                        </div>
                      </div>
                    ),
                  },
                //   {
                //     accessor: "birthdate",
                //     title: "Birth Date",
                //     sortable: true,
                //     render: ({ birthdate }) => (
                //       <span className="text-gray-600 dark:text-gray-300">
                //         {formatBirthdate(birthdate)}
                //       </span>
                //     ),
                //   },
                ]}
                totalRecords={customers.length}
                recordsPerPage={pageSize}
                page={page}
                onPageChange={setPage}
                recordsPerPageOptions={PAGE_SIZES}
                onRecordsPerPageChange={setPageSize}
                sortStatus={sortStatus}
                onSortStatusChange={setSortStatus}
                minHeight={200}
                paginationText={({ from, to, totalRecords }) => (
                  <span className="dark:text-white-light">
                    Showing {from} to {to} of {totalRecords} entries
                  </span>
                )}
                rowClassName={(record, index) =>
                  `transition-colors duration-100 ${
                    index % 2 === 0
                      ? "bg-gray-50/50 dark:bg-gray-800/50"
                      : "bg-white dark:bg-gray-900"
                  } hover:bg-gray-100 dark:hover:bg-gray-700`
                }
              />
            </div>
          )}

          <div className="flex justify-end mt-6">
            <button
              onClick={() => navigate("/insurance")}
              className="px-6 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-secondary dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
            >
              Back
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default ViewInsuranceCustomer;