import { UserTablo } from "@xtablo/shared/types/tablos.types";
import { Button } from "@xtablo/ui/components/button";
import { Users } from "lucide-react";
import { useState } from "react";
import { useCancelTabloInvite, usePendingTabloInvitesByTablo } from "src/hooks/tablo_invites";
import { useInviteUser } from "../hooks/invite";
import { useTabloMembers } from "../hooks/tablos";
import { useUser } from "../providers/UserStoreProvider";

interface TabloMembersSectionProps {
  tablo: UserTablo;
  isAdmin: boolean;
}

export const TabloMembersSection = ({ tablo, isAdmin }: TabloMembersSectionProps) => {
  const currentUser = useUser();
  const { data: members } = useTabloMembers(tablo.id);
  const { data: pendingInvites } = usePendingTabloInvitesByTablo(tablo.id);
  const { mutate: cancelInvite, isPending: isCancellingInvite } = useCancelTabloInvite();

  const [inviteEmail, setInviteEmail] = useState("");
  const { mutate: inviteUser, isPending: isInvitingUser } = useInviteUser();

  const filteredMembers = members?.filter(
    (member) => !pendingInvites?.some((invite) => invite.invited_email === member.email)
  );

  const handleSendInvite = () => {
    if (inviteEmail.trim()) {
      inviteUser({ email: inviteEmail, tablo_id: tablo.id });
      setInviteEmail("");
    }
  };

  const isEmailValid = (email: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground flex items-center gap-3">
            <Users className="w-8 h-8" />
            Membres
          </h1>
          <p className="text-muted-foreground mt-1">Gérez les membres de votre tablo</p>
        </div>
      </div>

      {/* Invite User Section - Only for Admins */}
      {isAdmin && (
        <>
          <div className="bg-card rounded-lg border border-border p-6">
            <h3 className="text-lg font-semibold text-foreground mb-4">Inviter un utilisateur</h3>
            <div className="flex space-x-2">
              <input
                type="email"
                value={inviteEmail}
                onChange={(e) => setInviteEmail(e.target.value)}
                placeholder="Email de l'utilisateur à inviter"
                className="flex-1 px-3 py-2 border border-input rounded-md shadow-sm placeholder-muted-foreground focus:outline-none focus:ring-primary focus:border-primary bg-background text-foreground"
              />
              {isInvitingUser ? (
                <div className="flex justify-center items-center">
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
                </div>
              ) : (
                <Button
                  type="button"
                  onClick={handleSendInvite}
                  disabled={!isEmailValid(inviteEmail)}
                >
                  Inviter
                </Button>
              )}
            </div>
          </div>

          {/* Pending Invites Section - Only for Admins */}
          {pendingInvites && pendingInvites.length > 0 && (
            <div className="bg-card rounded-lg border border-border p-6">
              <h3 className="text-lg font-semibold text-foreground mb-4">
                Invitations en attente
                <span className="ml-2 text-sm font-normal text-muted-foreground">
                  ({pendingInvites.length})
                </span>
              </h3>

              <div className="space-y-2">
                {pendingInvites.map((invite) => (
                  <div
                    key={invite.id}
                    className="flex items-center space-x-3 p-3 bg-orange-50 dark:bg-orange-950/20 rounded-lg border border-dashed border-orange-200 dark:border-orange-900/50"
                  >
                    <div className="w-10 h-10 bg-orange-100 dark:bg-orange-900/30 rounded-full flex items-center justify-center text-orange-600 dark:text-orange-400 text-sm font-medium">
                      <svg
                        className="w-5 h-5"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
                        />
                      </svg>
                    </div>
                    <div className="flex-1">
                      <span className="text-sm font-medium text-foreground">
                        {invite.invited_email}
                      </span>
                      <span className="text-xs text-muted-foreground ml-2">(En attente)</span>
                    </div>
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => cancelInvite({ tabloId: tablo.id, inviteId: invite.id })}
                      disabled={isCancellingInvite}
                    >
                      Retirer
                    </Button>
                  </div>
                ))}
              </div>
            </div>
          )}
        </>
      )}

      {/* Members List - Visible for All Users */}
      <div className="bg-card rounded-lg border border-border p-6">
        <h3 className="text-lg font-semibold text-foreground mb-4">
          Membres du tablo
          {filteredMembers && (
            <span className="ml-2 text-sm font-normal text-muted-foreground">
              ({filteredMembers.length})
            </span>
          )}
        </h3>

        <div className="space-y-2">
          {filteredMembers && filteredMembers.length > 0 ? (
            filteredMembers.map((member, index) => (
              <div key={index} className="flex items-center space-x-3 p-3 bg-muted rounded-lg">
                <div className="w-10 h-10 bg-primary rounded-full flex items-center justify-center text-primary-foreground text-sm font-medium">
                  {member.name.charAt(0).toUpperCase()}
                </div>
                <div className="flex-1">
                  <span className="text-sm font-medium text-foreground">{member.name}</span>
                  {member.is_admin ? (
                    <span className="text-xs text-muted-foreground ml-2">
                      {member.id === currentUser?.id ? "(Vous, Admin)" : "(Admin)"}
                    </span>
                  ) : (
                    <span className="text-xs text-muted-foreground ml-2">
                      {member.id === currentUser?.id ? "(Vous, Invité)" : "(Invité)"}
                    </span>
                  )}
                </div>
              </div>
            ))
          ) : (
            <p className="text-sm text-muted-foreground">Aucun membre trouvé</p>
          )}
        </div>
      </div>
    </div>
  );
};
