import { toast } from "@xtablo/shared";
import { TabloUpdate, UserTablo } from "@xtablo/shared/types/tablos.types";
import { Avatar, AvatarFallback, AvatarImage } from "@xtablo/ui/components/avatar";
import { Button } from "@xtablo/ui/components/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@xtablo/ui/components/dialog";
import { Input } from "@xtablo/ui/components/input";
import { Popover, PopoverContent, PopoverTrigger } from "@xtablo/ui/components/popover";
import { Loader2, Settings, Share2, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useInviteUser } from "../hooks/invite";
import { useCancelTabloInvite, usePendingTabloInvitesByTablo } from "../hooks/tablo_invites";
import { useTabloMembers, useUpdateTablo } from "../hooks/tablos";
import { useUser } from "../providers/UserStoreProvider";
import { ClickOutside } from "./ClickOutside";
import { ImageColorPicker } from "./ImageColorPicker";

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

export const TabloHeaderActions = ({ tablo, isAdmin }: TabloHeaderActionsProps) => {
  const { mutateAsync: updateTablo } = useUpdateTablo();
  const currentUser = useUser();
  const [isShareDialogOpen, setIsShareDialogOpen] = useState(false);
  const [inviteEmail, setInviteEmail] = useState("");

  // Settings state
  const [editData, setEditData] = useState<UserTablo | null>(tablo);
  const [isEditingName, setIsEditingName] = useState(false);
  const [creationMode, setCreationMode] = useState<"image" | "color">("color");
  const [selectedColor, setSelectedColor] = useState(tablo.color || "bg-blue-500");

  const nameInputRef = useRef<HTMLInputElement>(null);

  // Fetch members and invites for share dialog
  const { data: members } = useTabloMembers(tablo?.id || "");
  const { data: pendingInvites } = usePendingTabloInvitesByTablo(tablo?.id || "");
  const { mutate: cancelInvite, isPending: isCancellingInvite } = useCancelTabloInvite();
  const { mutate: inviteUser, isPending: isInvitingUser } = useInviteUser();

  useEffect(() => {
    setEditData(tablo);
    setSelectedColor(tablo.color || "bg-blue-500");
  }, [tablo]);

  // Auto-focus name input when editing
  useEffect(() => {
    if (isEditingName && nameInputRef.current) {
      nameInputRef.current.focus();
      nameInputRef.current.select();
    }
  }, [isEditingName]);

  const handleSaveSettings = async () => {
    if (editData && tablo) {
      const updatedTablo: TabloUpdate & { id: string } = {
        id: editData.id,
        name: editData.name,
        color: creationMode === "color" ? selectedColor : null,
      };
      try {
        await updateTablo(updatedTablo);
        toast.add(
          {
            title: "Tablo mis à jour",
            description: "Les modifications ont été enregistrées",
            type: "success",
          },
          { timeout: 3000 }
        );
      } catch (_error) {
        toast.add(
          {
            title: "Erreur",
            description: "Impossible de mettre à jour le tablo",
            type: "error",
          },
          { timeout: 5000 }
        );
      }
    }
  };

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

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

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

  return (
    <div className="inline-flex items-center gap-2">
      {/* Member Avatars */}
      {filteredMembers && filteredMembers.length > 0 && (
        <div className="flex items-center -space-x-2 mr-2">
          {filteredMembers.slice(0, 3).map((member) => {
            const avatarUrl =
              member.avatar_url ?? (member.id === currentUser.id ? currentUser.avatar_url : null);
            return (
              <Avatar
                key={member.id}
                className="w-7 h-7 border-2 border-background hover:z-10 transition-all cursor-pointer"
                onClick={() => setIsShareDialogOpen(true)}
                title={member.name}
              >
                {avatarUrl && <AvatarImage src={avatarUrl} alt={member.name} />}
                <AvatarFallback className="bg-primary text-primary-foreground text-[10px] font-medium">
                  {member.name.charAt(0).toUpperCase()}
                </AvatarFallback>
              </Avatar>
            );
          })}
          {filteredMembers.length > 3 && (
            <div
              className="w-7 h-7 border-2 border-background rounded-full bg-muted flex items-center justify-center text-[10px] font-medium text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"
              onClick={() => setIsShareDialogOpen(true)}
              title={`${filteredMembers.length - 3} autres membres`}
            >
              +{filteredMembers.length - 3}
            </div>
          )}
        </div>
      )}

      {/* Share Button */}
      {isAdmin && (
        <Button variant="default" size="sm" onClick={() => setIsShareDialogOpen(true)}>
          <Share2 className="w-4 h-4 mr-2" />
          Partager
        </Button>
      )}

      {/* Settings Popover */}
      {isAdmin && (
        <Popover>
          <PopoverTrigger asChild>
            <Button variant="outline" size="icon">
              <Settings className="w-4 h-4" />
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-96" align="end">
            <div className="space-y-4">
              <h3 className="text-lg font-semibold text-foreground">Paramètres</h3>

              {/* Name Edit */}
              <div>
                <label className="block text-base font-semibold text-gray-800 dark:text-gray-300 mb-2">
                  Nom du tablo
                </label>
                {isEditingName ? (
                  <ClickOutside onClickOutside={() => setIsEditingName(false)}>
                    <Input
                      ref={nameInputRef}
                      type="text"
                      value={editData?.name}
                      onChange={(e) =>
                        setEditData((prev) => (prev ? { ...prev, name: e.target.value } : null))
                      }
                      onKeyDown={(e) => {
                        if (e.key === "Enter") {
                          setIsEditingName(false);
                        }
                      }}
                      placeholder="Nom du tablo"
                    />
                  </ClickOutside>
                ) : (
                  <div
                    className="text-sm font-medium text-foreground cursor-text hover:text-primary hover:border-primary transition-colors border-2 border-dashed border-muted-foreground/30 rounded px-3 py-2"
                    onClick={() => setIsEditingName(true)}
                  >
                    {editData?.name}
                  </div>
                )}
              </div>

              {/* Color/Image Picker */}
              <div>
                <ImageColorPicker
                  creationMode={creationMode}
                  setCreationMode={setCreationMode}
                  selectedColor={selectedColor}
                  setSelectedColor={setSelectedColor}
                />
              </div>

              {/* Save Button */}
              <Button onClick={handleSaveSettings} className="w-full">
                Sauvegarder
              </Button>
            </div>
          </PopoverContent>
        </Popover>
      )}

      {/* Share Dialog */}
      <Dialog open={isShareDialogOpen} onOpenChange={setIsShareDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Partager le tablo</DialogTitle>
            <DialogDescription>Invitez des personnes à collaborer sur ce tablo</DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* Invite Input */}
            <div className="flex space-x-2">
              <Input
                type="email"
                value={inviteEmail}
                onChange={(e) => setInviteEmail(e.target.value)}
                placeholder="Email de l'utilisateur"
                className="flex-1"
              />
              {isInvitingUser ? (
                <div className="flex justify-center items-center px-4">
                  <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>

            {/* Pending Invites */}
            {pendingInvites && pendingInvites.length > 0 && (
              <div>
                <h4 className="text-sm font-semibold text-foreground mb-2">
                  Invitations en attente ({pendingInvites.length})
                </h4>
                <div className="space-y-2 max-h-32 overflow-y-auto">
                  {pendingInvites.map((invite) => (
                    <div
                      key={invite.id}
                      className="flex items-center space-x-2 p-2 bg-orange-50 dark:bg-orange-950/20 rounded-lg border border-dashed border-orange-200 dark:border-orange-900/50"
                    >
                      <div className="w-8 h-8 bg-orange-100 dark:bg-orange-900/30 rounded-full flex items-center justify-center text-orange-600 dark:text-orange-400 text-xs">
                        <svg
                          className="w-4 h-4"
                          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 min-w-0">
                        <span className="text-xs font-medium text-foreground truncate block">
                          {invite.invited_email}
                        </span>
                      </div>
                      <Button
                        size="icon"
                        variant="ghost"
                        className="h-8 w-8"
                        onClick={() => cancelInvite({ tabloId: tablo.id, inviteId: invite.id })}
                        disabled={isCancellingInvite}
                        title="Retirer l'invitation"
                      >
                        {isCancellingInvite ? (
                          <Loader2 className="h-4 w-4 animate-spin" />
                        ) : (
                          <X className="h-4 w-4 text-muted-foreground" />
                        )}
                      </Button>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Members List */}
            {filteredMembers && filteredMembers.length > 0 && (
              <div>
                <h4 className="text-sm font-semibold text-foreground mb-2">
                  Membres ({filteredMembers.length})
                </h4>
                <div className="space-y-2 max-h-48 overflow-y-auto">
                  {filteredMembers.map((member, index) => {
                    const avatarUrl =
                      member.avatar_url ??
                      (member.id === currentUser.id ? currentUser.avatar_url : null);
                    return (
                      <div
                        key={index}
                        className="flex items-center space-x-2 p-2 bg-muted rounded-lg"
                      >
                        <Avatar className="w-8 h-8">
                          {avatarUrl && <AvatarImage src={avatarUrl} alt={member.name} />}
                          <AvatarFallback className="bg-primary text-primary-foreground text-xs font-medium">
                            {member.name.charAt(0).toUpperCase()}
                          </AvatarFallback>
                        </Avatar>
                        <div className="flex-1 min-w-0">
                          <span className="text-xs font-medium text-foreground truncate block">
                            {member.name}
                          </span>
                          <span className="text-xs text-muted-foreground">
                            {member.is_admin ? "Admin" : "Invité"}
                          </span>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
};
