import { FormEvent, useEffect, useState } from "react";
import { KeyRound, Save, UserCircle } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { HelpLink } from "@/components/HelpLink";
import { updateCurrentUser } from "../api";
import type { AuthUser } from "../types";

type ProfilePageProps = {
  currentUser: AuthUser;
  onUserUpdated: (user: AuthUser) => void;
};

export function ProfilePage({ currentUser, onUserUpdated }: ProfilePageProps) {
  const [username, setUsername] = useState(currentUser.username);
  const [displayName, setDisplayName] = useState(currentUser.display_name);
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    setUsername(currentUser.username);
    setDisplayName(currentUser.display_name);
  }, [currentUser]);

  async function submit(event: FormEvent) {
    event.preventDefault();

    const wantsPasswordChange = newPassword.length > 0 || confirmPassword.length > 0 || currentPassword.length > 0;

    if (wantsPasswordChange && newPassword !== confirmPassword) {
      toast.error("Passwörter stimmen nicht überein");
      return;
    }

    if (wantsPasswordChange && newPassword.length < 6) {
      toast.error("Passwort ist zu kurz", {
        description: "Das neue Passwort muss mindestens 6 Zeichen lang sein."
      });
      return;
    }

    setSaving(true);

    try {
      const result = await updateCurrentUser({
        username,
        displayName,
        currentPassword: wantsPasswordChange ? currentPassword : undefined,
        newPassword: wantsPasswordChange ? newPassword : undefined
      });
      onUserUpdated(result.user);
      setCurrentPassword("");
      setNewPassword("");
      setConfirmPassword("");
      toast.success("Profil gespeichert");
    } catch (error) {
      toast.error("Profil konnte nicht gespeichert werden", {
        description: error instanceof Error ? error.message : "Unbekannter Fehler"
      });
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="space-y-4">
      <div>
        <h2 className="text-xl font-semibold tracking-normal sm:text-2xl">Profil</h2>
        <p className="text-sm text-muted-foreground">Benutzername, voller Name und Passwort deines Accounts.</p>
      </div>

      <Card>
        <CardHeader className="p-4">
          <div className="flex items-start justify-between gap-3">
            <div className="flex items-center gap-2">
              <UserCircle className="size-5 text-muted-foreground" />
              <CardTitle>Accountdaten</CardTitle>
            </div>
            <HelpLink anchor="profil" label="Hilfe zum Profil" />
          </div>
          <CardDescription>Der Benutzername wird beim Login verwendet. Dein voller Name wird in der App angezeigt.</CardDescription>
        </CardHeader>
        <CardContent className="px-4 pb-4">
          <form className="space-y-5" onSubmit={submit}>
            <div className="grid gap-3 md:grid-cols-2">
              <div className="space-y-2">
                <label className="text-sm font-medium" htmlFor="profile-username">
                  Benutzername
                </label>
                <Input id="profile-username" value={username} onChange={(event) => setUsername(event.currentTarget.value)} required />
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium" htmlFor="profile-display-name">
                  Voller Name
                </label>
                <Input id="profile-display-name" value={displayName} onChange={(event) => setDisplayName(event.currentTarget.value)} required />
              </div>
            </div>

            <div className="rounded-md border bg-muted/30 p-3">
              <div className="mb-3 flex items-center gap-2">
                <KeyRound className="size-4 text-muted-foreground" />
                <p className="text-sm font-medium">Passwort ändern</p>
              </div>
              <div className="grid gap-3 md:grid-cols-3">
                <div className="space-y-2">
                  <label className="text-sm font-medium" htmlFor="profile-current-password">
                    Aktuelles Passwort
                  </label>
                  <Input
                    id="profile-current-password"
                    type="password"
                    value={currentPassword}
                    onChange={(event) => setCurrentPassword(event.currentTarget.value)}
                    autoComplete="current-password"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium" htmlFor="profile-new-password">
                    Neues Passwort
                  </label>
                  <Input
                    id="profile-new-password"
                    type="password"
                    value={newPassword}
                    onChange={(event) => setNewPassword(event.currentTarget.value)}
                    autoComplete="new-password"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium" htmlFor="profile-confirm-password">
                    Wiederholen
                  </label>
                  <Input
                    id="profile-confirm-password"
                    type="password"
                    value={confirmPassword}
                    onChange={(event) => setConfirmPassword(event.currentTarget.value)}
                    autoComplete="new-password"
                  />
                </div>
              </div>
            </div>

            <div className="flex justify-end">
              <Button type="submit" disabled={saving}>
                <Save className="size-4" />
                {saving ? "Speichert..." : "Profil speichern"}
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
