import { type LocalAccount } from "@/repository/account";
import { useAuth } from "@/store/auth";
import { CirclePlus } from "lucide-react";
import { useCallback, type FC } from "react";
import { Link, useLocation } from "react-router";
import Avatar from "../Avatar";

const AccountList: FC = () => {
  const accounts = useAuth((state) => state.accounts);
  const updateActiveAccount = useAuth((state) => state.updateActiveAccount);

  const location = useLocation();

  const handleAccountSelect = useCallback(
    (account: LocalAccount) => {
      updateActiveAccount(account);
    },
    [updateActiveAccount],
  );

  return (
    <>
      {accounts.map((account) => (
        <div
          key={account.accountId}
          onClick={() => handleAccountSelect(account)}
          className="flex flex-row items-center p-4 border-gray-200 dark:border-gray-700/65 border-b border-r-0 border-l-0 select-none cursor-pointer hover:bg-gray-50/50 dark:hover:bg-gray-800/10 transition-colors mb-0"
        >
          <div>
            <div className="rounded-full w-10 h-10 overflow-hidden bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-gray-200 mr-3 ring ring-gray-400 dark:ring dark:ring-gray-500">
              <Avatar iconSize={8} avatarId={account.profilePicture ?? null} />
            </div>
          </div>
          <div className="flex flex-col">
            <p className="text-base text-gray-900 dark:text-gray-200">
              {account.label}
            </p>
            <p className="text-gray-500 dark:text-gray-600 text-sm">
              {account.email}
            </p>
          </div>
        </div>
      ))}
      <Link to="/auth/login" state={location.state}>
        <div className="flex flex-row items-center p-4 border-gray-200 dark:border-gray-700/65 border-b border-r-0 border-l-0 select-none cursor-pointer hover:bg-gray-50/50 dark:hover:bg-gray-800/10 transition-colors mb-0">
          <div>
            <div className="rounded-full p-2 text-gray-900 dark:text-gray-200 mr-3">
              <CirclePlus />
            </div>
          </div>
          <p className="text-base text-gray-900 dark:text-gray-200">
            Add new account
          </p>
        </div>
      </Link>
    </>
  );
};

export default AccountList;
