import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Button, Input } from "@shared/ui";
import { changePassword, updateProfile, uploadAvatar, type ProfileResponse } from "../api/profileApi";

interface ProfileEditorProps {
  profile: ProfileResponse;
}

export function ProfileEditor({ profile }: ProfileEditorProps): JSX.Element {
  const queryClient = useQueryClient();
  const [displayName, setDisplayName] = useState(profile.profile.display_name);
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [message, setMessage] = useState("");

  const updateMutation = useMutation({
    mutationFn: () => updateProfile({ display_name: displayName }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["profile-me"] });
      setMessage("Profile updated");
    }
  });

  const passwordMutation = useMutation({
    mutationFn: () => changePassword({ current_password: currentPassword, new_password: newPassword }),
    onSuccess: () => {
      setCurrentPassword("");
      setNewPassword("");
      setMessage("Password changed");
    },
    onError: () => setMessage("Invalid current password")
  });

  const avatarMutation = useMutation({
    mutationFn: (file: File) => uploadAvatar(file),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["profile-me"] });
      setMessage("Avatar uploaded");
    },
    onError: () => setMessage("Avatar upload failed")
  });

  return (
    <section style={{ display: "grid", gap: "1rem", maxWidth: 480 }}>
      <h2>Edit profile</h2>
      <label>
        Display name
        <Input value={displayName} onChange={(event) => setDisplayName(event.target.value)} />
      </label>
      <Button type="button" onClick={() => updateMutation.mutate()}>
        Save name
      </Button>

      <label>
        Avatar
        <Input
          type="file"
          accept="image/png,image/jpeg,image/webp"
          onChange={(event) => {
            const file = event.target.files?.[0];
            if (file) {
              avatarMutation.mutate(file);
            }
          }}
        />
      </label>

      <div style={{ display: "grid", gap: "0.5rem" }}>
        <h3>Change password</h3>
        <Input
          type="password"
          placeholder="Current password"
          value={currentPassword}
          onChange={(event) => setCurrentPassword(event.target.value)}
        />
        <Input
          type="password"
          placeholder="New password"
          value={newPassword}
          onChange={(event) => setNewPassword(event.target.value)}
        />
        <Button type="button" onClick={() => passwordMutation.mutate()}>
          Change password
        </Button>
      </div>

      {message ? <p>{message}</p> : null}
    </section>
  );
}
