import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  Users2,
  Search,
  UserPlus,
  Check,
  X,
  Loader2,
  Clock,
  LogIn,
  AtSign,
} from "lucide-react";
import { useAuthStore } from "../stores/authStore";
import {
  useFriendsStore,
  SearchResult,
} from "../stores/friendsStore";
import { ApiError } from "../lib/apiClient";
import { Card, CardContent } from "../components/ui/card";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Avatar } from "../components/ui/avatar";
import { PageHeader } from "../components/PageHeader";

export default function Friends() {
  const navigate = useNavigate();
  const { status, user, updateAccount } = useAuthStore();
  const { friends, incoming, outgoing, load, search, sendRequest, accept, decline, unfriend } =
    useFriendsStore();

  const [query, setQuery] = useState("");
  const [results, setResults] = useState<SearchResult[]>([]);
  const [searching, setSearching] = useState(false);
  const [usernameInput, setUsernameInput] = useState("");
  const [savingUsername, setSavingUsername] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (status === "authenticated") load();
  }, [status, load]);

  if (status !== "authenticated") {
    return (
      <div className="p-5 space-y-5 relative z-10">
        <PageHeader title="Amis" />
        <Card className="border-0 shadow-lg bg-background/90 backdrop-blur-md">
          <CardContent className="p-6 text-center space-y-4">
            <Users2 className="w-14 h-14 mx-auto opacity-20" />
            <p className="font-bold">
              Connectez-vous pour ajouter des amis et les retrouver dans vos
              parties.
            </p>
            <Button
              className="w-full h-12 rounded-2xl font-black"
              onClick={() => navigate("/login")}
            >
              <LogIn className="w-5 h-5 mr-2" />
              Se connecter
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  const handleSearch = async () => {
    setError(null);
    setSearching(true);
    try {
      setResults(await search(query));
    } catch {
      setError("Recherche impossible.");
    } finally {
      setSearching(false);
    }
  };

  const handleSend = async (username: string) => {
    setError(null);
    try {
      await sendRequest(username);
      setResults((prev) =>
        prev.map((r) =>
          r.username === username ? { ...r, relationship: "pending_out" } : r,
        ),
      );
    } catch (e) {
      const code = e instanceof ApiError ? e.message : "";
      setError(
        code === "already_friends"
          ? "Vous êtes déjà amis."
          : code === "request_already_exists"
            ? "Demande déjà envoyée."
            : "Impossible d'envoyer la demande.",
      );
    }
  };

  const handleSaveUsername = async () => {
    const u = usernameInput.trim();
    if (!u) return;
    setSavingUsername(true);
    setError(null);
    try {
      await updateAccount({ username: u });
    } catch (e) {
      const code = e instanceof ApiError ? e.message : "";
      setError(
        code === "username_taken"
          ? "Ce pseudo est déjà pris."
          : "Impossible d'enregistrer le pseudo.",
      );
    } finally {
      setSavingUsername(false);
    }
  };

  return (
    <div className="p-5 space-y-5 relative z-10">
      <PageHeader title="Amis" />

      {error && (
        <p className="text-sm text-destructive font-medium bg-destructive/10 rounded-xl p-3">
          {error}
        </p>
      )}

      {/* Prompt to set a username so others can find you */}
      {!user?.username ? (
        <Card className="border-0 shadow-lg bg-primary/5 backdrop-blur-md">
          <CardContent className="p-4 space-y-3">
            <p className="text-sm font-bold flex items-center">
              <AtSign className="w-4 h-4 mr-2 text-primary" />
              Choisissez un pseudo pour que vos amis vous trouvent
            </p>
            <div className="flex space-x-2">
              <Input
                value={usernameInput}
                onChange={(e) => setUsernameInput(e.target.value)}
                placeholder="votre_pseudo"
                className="h-12"
              />
              <Button
                onClick={handleSaveUsername}
                disabled={savingUsername || !usernameInput.trim()}
                className="rounded-2xl font-bold"
              >
                {savingUsername ? (
                  <Loader2 className="w-5 h-5 animate-spin" />
                ) : (
                  <Check className="w-5 h-5" />
                )}
              </Button>
            </div>
          </CardContent>
        </Card>
      ) : (
        <p className="text-sm text-muted-foreground px-2">
          Votre pseudo : <span className="font-bold">@{user.username}</span>
        </p>
      )}

      {/* Search */}
      <div className="flex space-x-2">
        <Input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && handleSearch()}
          placeholder="Rechercher un pseudo…"
          className="h-12"
        />
        <Button
          onClick={handleSearch}
          disabled={searching || query.trim().length < 2}
          className="rounded-2xl font-bold"
        >
          {searching ? (
            <Loader2 className="w-5 h-5 animate-spin" />
          ) : (
            <Search className="w-5 h-5" />
          )}
        </Button>
      </div>

      {results.length > 0 && (
        <div className="space-y-2">
          {results.map((r) => (
            <Card key={r.id} className="border-0 shadow-md bg-background/90">
              <CardContent className="p-3 flex items-center justify-between">
                <div className="flex items-center min-w-0">
                  <Avatar src={r.avatarUrl ?? undefined} name={r.displayName} size="md" className="mr-3" />
                  <div className="min-w-0">
                    <p className="font-bold truncate">{r.displayName}</p>
                    {r.username && (
                      <p className="text-xs text-muted-foreground truncate">
                        @{r.username}
                      </p>
                    )}
                  </div>
                </div>
                {r.relationship === "friends" ? (
                  <span className="text-xs font-bold text-emerald-600">Ami</span>
                ) : r.relationship === "pending_out" ? (
                  <span className="text-xs font-bold text-muted-foreground">
                    Envoyée
                  </span>
                ) : r.relationship === "pending_in" ? (
                  <span className="text-xs font-bold text-primary">
                    Vous a ajouté
                  </span>
                ) : (
                  <Button
                    size="sm"
                    className="rounded-full font-bold"
                    onClick={() => r.username && handleSend(r.username)}
                  >
                    <UserPlus className="w-4 h-4 mr-1" />
                    Ajouter
                  </Button>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Incoming requests */}
      {incoming.length > 0 && (
        <section className="space-y-2">
          <h2 className="text-lg font-bold px-1">Demandes reçues</h2>
          {incoming.map((r) => (
            <Card key={r.friendshipId} className="border-0 shadow-md bg-background/90">
              <CardContent className="p-3 flex items-center justify-between">
                <div className="flex items-center min-w-0">
                  <Avatar src={r.user.avatarUrl ?? undefined} name={r.user.displayName} size="md" className="mr-3" />
                  <div className="min-w-0">
                    <p className="font-bold truncate">{r.user.displayName}</p>
                    {r.user.username && (
                      <p className="text-xs text-muted-foreground truncate">
                        @{r.user.username}
                      </p>
                    )}
                  </div>
                </div>
                <div className="flex space-x-1 shrink-0">
                  <Button
                    size="icon"
                    variant="ghost"
                    className="text-green-600 bg-green-500/10 hover:bg-green-500/20 rounded-xl"
                    onClick={() => accept(r.friendshipId)}
                  >
                    <Check className="w-5 h-5" />
                  </Button>
                  <Button
                    size="icon"
                    variant="ghost"
                    className="text-destructive hover:bg-destructive/10 rounded-xl"
                    onClick={() => decline(r.friendshipId)}
                  >
                    <X className="w-5 h-5" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </section>
      )}

      {/* Outgoing requests */}
      {outgoing.length > 0 && (
        <section className="space-y-2">
          <h2 className="text-lg font-bold px-1">Demandes envoyées</h2>
          {outgoing.map((r) => (
            <Card key={r.friendshipId} className="border-0 shadow-sm bg-background/70">
              <CardContent className="p-3 flex items-center justify-between">
                <div className="flex items-center min-w-0">
                  <Avatar src={r.user.avatarUrl ?? undefined} name={r.user.displayName} size="md" className="mr-3 opacity-70" />
                  <p className="font-bold truncate">{r.user.displayName}</p>
                </div>
                <span className="flex items-center text-xs font-bold text-muted-foreground shrink-0">
                  <Clock className="w-3.5 h-3.5 mr-1" />
                  En attente
                </span>
              </CardContent>
            </Card>
          ))}
        </section>
      )}

      {/* Friends list */}
      <section className="space-y-2">
        <h2 className="text-lg font-bold px-1">
          Mes amis {friends.length > 0 && `(${friends.length})`}
        </h2>
        {friends.length === 0 ? (
          <div className="text-center text-muted-foreground py-8 bg-background/60 backdrop-blur-sm rounded-[2rem]">
            <Users2 className="w-12 h-12 mx-auto mb-2 opacity-20" />
            <p className="text-sm font-medium">
              Aucun ami pour l'instant. Recherchez un pseudo ci-dessus.
            </p>
          </div>
        ) : (
          friends.map((f) => (
            <Card key={f.friendshipId} className="border-0 shadow-md bg-background/90">
              <CardContent className="p-3 flex items-center justify-between">
                <div className="flex items-center min-w-0">
                  <Avatar src={f.user.avatarUrl ?? undefined} name={f.user.displayName} size="md" className="mr-3" />
                  <div className="min-w-0">
                    <p className="font-bold truncate">{f.user.displayName}</p>
                    {f.user.username && (
                      <p className="text-xs text-muted-foreground truncate">
                        @{f.user.username}
                      </p>
                    )}
                  </div>
                </div>
                <Button
                  size="sm"
                  variant="ghost"
                  className="text-destructive hover:bg-destructive/10 rounded-full text-xs font-bold shrink-0"
                  onClick={() => unfriend(f.friendshipId)}
                >
                  Retirer
                </Button>
              </CardContent>
            </Card>
          ))
        )}
      </section>
    </div>
  );
}
