import { toast } from "@xtablo/shared";
import { Button } from "@xtablo/ui/components/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@xtablo/ui/components/card";
import { CheckCircle2Icon, XCircleIcon } from "lucide-react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useJoinTablo } from "../hooks/invite";
import { useUser } from "../providers/UserStoreProvider";

export const JoinPage = () => {
  const [searchParams] = useSearchParams();
  const tabloName = decodeURIComponent(searchParams.get("tablo_name") || "");
  const token = searchParams.get("token");

  const navigate = useNavigate();
  const user = useUser();
  const joinTablo = useJoinTablo();

  return (
    <div className="min-h-screen flex items-center justify-center bg-background p-4">
      <div className="max-w-md w-full">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-foreground">
            Rejoindre le tablo &quot;{tabloName}&quot;
          </h1>
        </div>

        <Card className="transition-shadow hover:shadow-lg">
          <CardHeader className="text-center">
            <CardTitle className="text-2xl">{tabloName}</CardTitle>
            <CardDescription>Vous avez été invité(e) à rejoindre ce tablo</CardDescription>
          </CardHeader>

          <CardContent className="space-y-4">
            <Button
              onClick={() => {
                if (!user || !token) {
                  toast.add(
                    {
                      title: "Erreur",
                      description: "Vous n'avez pas les permissions requises",
                      type: "error",
                    },
                    { timeout: 2000 }
                  );
                  return;
                }
                joinTablo(
                  { token },
                  {
                    onSuccess: ({ tablo_id }) => {
                      navigate(`/tablos/${tablo_id}`);
                    },
                    onError: (error) => {
                      console.error(error);
                      toast.add(
                        {
                          title: "Erreur",
                          description: "Une erreur est survenue.",
                          type: "error",
                        },
                        { timeout: 2000 }
                      );
                    },
                  }
                );
              }}
              className="w-full"
              size="lg"
            >
              <CheckCircle2Icon className="w-5 h-5 mr-2" />
              Accepter l&apos;invitation
            </Button>

            <Button onClick={() => navigate("/")} variant="outline" className="w-full" size="lg">
              <XCircleIcon className="w-5 h-5 mr-2" />
              Refuser
            </Button>
          </CardContent>
        </Card>
      </div>
    </div>
  );
};
