import { useOAuthContext } from "@/context/oauth";
import { type LocalAccount } from "@/repository/account";
import { useAuth } from "@/store/auth";
import { CirclePlus, User } from "lucide-react";
import { useCallback, type FC } from "react";
import { Link, useLocation } from "react-router-dom";

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

  const location = useLocation();

  const oauth = useOAuthContext();

  const handleAccountSelect = useCallback(
    (account: LocalAccount) => {
      oauth.selectSession(account.access);
      updateActiveAccount(account);
    },
    [oauth, 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">
              {account.profilePicture ? (
                <img
                  src={account.profilePicture}
                  className="w-full h-full flex-1 object-cover"
                  alt="profile"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center">
                  <User />
                </div>
              )}
            </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="/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;
