import { FormEvent, useEffect, useMemo, useState } from "react";
import { Link, useLocation, useParams } from "wouter";
import { AlertCircle, ArrowLeft, Building2, Loader2, Mail, UserPlus } from "lucide-react";

import { useAuth } from "@/_core/hooks/useAuth";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import DataPrivacyValidationDialog from "@/components/DataPrivacyValidationDialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { trpc } from "@/lib/trpc";
import { buildDataPrivacyConsent } from "@shared/privacyCompliance";

function getReasonMessage(reason: string | null | undefined) {
  switch (reason) {
    case "used":
      return "Cette invitation a déjà été utilisée.";
    case "revoked":
      return "Cette invitation a été remplacée par une nouvelle.";
    case "expired":
      return "Cette invitation a expiré.";
    case "already_registered":
      return "Cette association a déjà activé son espace.";
    default:
      return "Cette invitation n'est plus valide.";
  }
}

export default function AssociationInvitation() {
  const params = useParams<{ token: string }>();
  const [, setLocation] = useLocation();
  const invitationToken = params?.token || "";
  const { register, loading, error } = useAuth();
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");
  const [privacyDialogOpen, setPrivacyDialogOpen] = useState(false);

  const invitationQuery = trpc.associationInvitation.getPublic.useQuery(
    { token: invitationToken },
    {
      retry: false,
      enabled: Boolean(invitationToken),
    }
  );

  const invitation = invitationQuery.data;
  const invalidReason = invitation && !invitation.valid ? getReasonMessage(invitation.invalidReason) : null;

  useEffect(() => {
    if (invitation?.association && !name) {
      setName(invitation.association.nomRepresentant || invitation.association.nomAssociation);
    }
  }, [invitation, name]);

  const title = useMemo(() => {
    if (invitation?.association?.nomAssociation) {
      return `Activation de ${invitation.association.nomAssociation}`;
    }
    return "Activation de l'espace association";
  }, [invitation]);

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!invitation?.valid || !invitation.association.emailOfficiel) return;

    setPrivacyDialogOpen(true);
  };

  const submitInvitationRegistration = async () => {
    if (!invitation?.valid || !invitation.association.emailOfficiel) return;

    await register({
      name,
      email: invitation.association.emailOfficiel,
      password,
      invitationToken,
      privacyConsent: buildDataPrivacyConsent("register_account"),
    });

    setLocation("/dashboard");
  };

  return (
    <div className="min-h-screen bg-muted/30">
      <header className="border-b border-border bg-white">
        <div className="container py-4">
          <div className="flex items-center justify-between">
            <Link href="/" className="flex flex-col">
              <span className="text-xs text-muted-foreground uppercase tracking-wider">Republique Francaise</span>
              <span className="text-lg font-bold text-primary">Portail Associations</span>
            </Link>
            <Link href="/" className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-primary">
              <ArrowLeft className="h-4 w-4" />
              Accueil
            </Link>
          </div>
        </div>
      </header>

      <main className="container flex min-h-[calc(100vh-73px)] items-center justify-center py-10">
        <Card className="w-full max-w-xl shadow-sm">
          <CardHeader>
            <CardTitle>{title}</CardTitle>
            <CardDescription>
              Active l'espace portail de l'association à partir de cette invitation sécurisée.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {invitationQuery.isLoading ? (
              <div className="flex items-center justify-center py-10">
                <Loader2 className="h-8 w-8 animate-spin text-primary" />
              </div>
            ) : null}

            {invitationQuery.error ? (
              <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>{invitationQuery.error.message}</AlertDescription>
              </Alert>
            ) : null}

            {invalidReason ? (
              <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>{invalidReason}</AlertDescription>
              </Alert>
            ) : null}

            {invitation?.association ? (
              <div className="rounded-lg border bg-background p-4 space-y-2">
                <div className="flex items-start gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10 text-primary">
                    <Building2 className="h-5 w-5" />
                  </div>
                  <div>
                    <p className="font-medium">{invitation.association.nomAssociation}</p>
                    <p className="text-sm text-muted-foreground">
                      {invitation.association.ville || "Commune non renseignée"}
                    </p>
                  </div>
                </div>
                {invitation.association.emailOfficiel ? (
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <Mail className="h-4 w-4" />
                    {invitation.association.emailOfficiel}
                  </div>
                ) : null}
              </div>
            ) : null}

            {invitation?.valid ? (
              <form onSubmit={handleSubmit} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="name">Nom du référent</Label>
                  <Input
                    id="name"
                    value={name}
                    onChange={(event) => setName(event.target.value)}
                    minLength={2}
                    autoComplete="name"
                    required
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="email">Email officiel</Label>
                  <Input
                    id="email"
                    type="email"
                    value={invitation.association.emailOfficiel || ""}
                    disabled
                    readOnly
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="password">Mot de passe</Label>
                  <Input
                    id="password"
                    type="password"
                    value={password}
                    onChange={(event) => setPassword(event.target.value)}
                    autoComplete="new-password"
                    minLength={8}
                    required
                  />
                </div>

                {error ? (
                  <Alert variant="destructive">
                    <AlertCircle className="h-4 w-4" />
                    <AlertDescription>{error.message}</AlertDescription>
                  </Alert>
                ) : null}

                <Button type="submit" className="w-full gap-2" disabled={loading}>
                  {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <UserPlus className="h-4 w-4" />}
                  Activer l'espace association
                </Button>
              </form>
            ) : null}
          </CardContent>
        </Card>
      </main>
      <DataPrivacyValidationDialog
        open={privacyDialogOpen}
        onOpenChange={setPrivacyDialogOpen}
        context="register_account"
        confirmLabel="Valider et activer le compte"
        onConfirm={() => {
          void submitInvitationRegistration();
        }}
      />
    </div>
  );
}
