import { useState, type FormEvent } from "react";
import { useAuth, ApiError } from "../context/AuthContext";
import { useDocumentTitle } from "../hooks/useDocumentTitle";
import { authUpdateProfile } from "../api";
import { SidebarNav } from "./CreatorDashboard";
import dashStyles from "./CreatorDashboard.module.css";
import styles from "./CreatorSettings.module.css";

export default function CreatorSettings() {
  useDocumentTitle("Settings");
  const { user, token } = useAuth();

  // Profile fields
  const [displayName, setDisplayName] = useState(user?.display_name ?? "");
  const [profileMsg, setProfileMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [profileSubmitting, setProfileSubmitting] = useState(false);

  // Password fields
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [passwordMsg, setPasswordMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [passwordSubmitting, setPasswordSubmitting] = useState(false);

  const handleProfileSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setProfileMsg(null);

    if (!displayName.trim()) {
      setProfileMsg({ type: "error", text: "Display name cannot be empty." });
      return;
    }

    if (!token) return;
    setProfileSubmitting(true);
    try {
      await authUpdateProfile(token, { display_name: displayName.trim() });
      setProfileMsg({ type: "success", text: "Profile updated." });
    } catch (err) {
      setProfileMsg({
        type: "error",
        text: err instanceof ApiError ? err.detail : "Failed to update profile.",
      });
    } finally {
      setProfileSubmitting(false);
    }
  };

  const handlePasswordSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setPasswordMsg(null);

    if (!currentPassword || !newPassword) {
      setPasswordMsg({ type: "error", text: "Current and new password are required." });
      return;
    }
    if (newPassword.length < 8) {
      setPasswordMsg({ type: "error", text: "New password must be at least 8 characters." });
      return;
    }
    if (newPassword !== confirmPassword) {
      setPasswordMsg({ type: "error", text: "New passwords don't match." });
      return;
    }

    if (!token) return;
    setPasswordSubmitting(true);
    try {
      await authUpdateProfile(token, {
        current_password: currentPassword,
        new_password: newPassword,
      });
      setPasswordMsg({ type: "success", text: "Password changed successfully." });
      setCurrentPassword("");
      setNewPassword("");
      setConfirmPassword("");
    } catch (err) {
      setPasswordMsg({
        type: "error",
        text: err instanceof ApiError ? err.detail : "Failed to change password.",
      });
    } finally {
      setPasswordSubmitting(false);
    }
  };

  return (
    <div className={dashStyles.layout}>
      <SidebarNav />
      <div className={dashStyles.content}>
        <h1 className={styles.heading}>Settings</h1>

        {/* Profile section */}
        <div className={styles.section}>
          <h2 className={styles.sectionTitle}>Profile</h2>
          {profileMsg && (
            <div className={profileMsg.type === "error" ? styles.error : styles.success}>
              {profileMsg.text}
            </div>
          )}
          <form onSubmit={handleProfileSubmit} className={styles.fieldGroup}>
            <label className={styles.label}>
              Display Name
              <input
                type="text"
                className={styles.input}
                value={displayName}
                onChange={(e) => setDisplayName(e.target.value)}
              />
            </label>
            <label className={styles.label}>
              Email
              <input
                type="email"
                className={styles.inputReadonly}
                value={user?.email ?? ""}
                readOnly
                tabIndex={-1}
              />
            </label>
            <button type="submit" className={styles.button} disabled={profileSubmitting}>
              {profileSubmitting ? "Saving…" : "Save Profile"}
            </button>
          </form>
        </div>

        {/* Password section */}
        <div className={styles.section}>
          <h2 className={styles.sectionTitle}>Change Password</h2>
          {passwordMsg && (
            <div className={passwordMsg.type === "error" ? styles.error : styles.success}>
              {passwordMsg.text}
            </div>
          )}
          <form onSubmit={handlePasswordSubmit} className={styles.fieldGroup}>
            <label className={styles.label}>
              Current Password
              <input
                type="password"
                className={styles.input}
                value={currentPassword}
                onChange={(e) => setCurrentPassword(e.target.value)}
                autoComplete="current-password"
              />
            </label>
            <label className={styles.label}>
              New Password
              <input
                type="password"
                className={styles.input}
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                autoComplete="new-password"
              />
            </label>
            <label className={styles.label}>
              Confirm New Password
              <input
                type="password"
                className={styles.input}
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                autoComplete="new-password"
              />
            </label>
            <button type="submit" className={styles.button} disabled={passwordSubmitting}>
              {passwordSubmitting ? "Changing…" : "Change Password"}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}
