import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import api from "../api/client";

export default function UserForm() {
  const { id } = useParams();
  const isEdit = Boolean(id);
  const navigate = useNavigate();

  const [email, setEmail] = useState("");
  const [displayName, setDisplayName] = useState("");
  const [photoUrl, setPhotoUrl] = useState("");
  const [uid, setUid] = useState("");
  const [phoneNumber, setPhoneNumber] = useState("");
  const [status, setStatus] = useState("");
  const [bio, setBio] = useState("");
  const [userTitle, setUserTitle] = useState("");
  const [settingsPIN, setSettingsPIN] = useState("");
  const [quickSettingsPIN, setQuickSettingsPIN] = useState("");

  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    if (isEdit) loadUser();
  }, [id]);

  const loadUser = async () => {
    setLoading(true);
    try {
      const user = await api.get(`/users/${id}`);
      setEmail(user.email || "");
      setDisplayName(user.display_name || "");
      setPhotoUrl(user.photo_url || "");
      setUid(user.uid || "");
      setPhoneNumber(user.phone_number || "");
      setStatus(user.status || "");
      setBio(user.bio || "");
      setUserTitle(user.userTitle || "");
      setSettingsPIN(user.settingsPIN || "");
      setQuickSettingsPIN(user.quickSettingsPIN || "");
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSaving(true);
    setError("");

    try {
      const body = {
        email,
        display_name: displayName,
        photo_url: photoUrl,
        uid,
        phone_number: phoneNumber,
        status,
        bio,
        userTitle,
        settingsPIN,
        quickSettingsPIN,
      };

      let userId = id;
      if (isEdit) {
        await api.put(`/users/${id}`, body);
      } else {
        const created = await api.post("/users", body);
        userId = created.id;
      }

      navigate(`/users/${userId}`);
    } catch (err) {
      setError(err.message);
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>;
  }

  const inputClass = "w-full px-3 py-2 rounded-md text-sm border";
  const inputStyle = {
    backgroundColor: "var(--bg-input)",
    borderColor: "var(--border-input)",
    color: "var(--text-primary)",
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>
          {isEdit ? "Edit User" : "Add User"}
        </h1>
        <div className="flex gap-3">
          <button
            type="button"
            onClick={() => navigate(isEdit ? `/users/${id}` : "/users")}
            className="px-4 py-2 text-sm rounded-md hover:opacity-80 transition-colors"
            style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-primary)" }}
          >
            Cancel
          </button>
          <button
            type="submit"
            form="user-form"
            disabled={saving}
            className="px-4 py-2 text-sm rounded-md hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
          >
            {saving ? "Saving..." : isEdit ? "Update User" : "Create User"}
          </button>
        </div>
      </div>

      {error && (
        <div
          className="text-sm rounded-md p-3 mb-4 border"
          style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}
        >
          {error}
        </div>
      )}

      <form id="user-form" onSubmit={handleSubmit}>
        <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
          {/* ===== Left Column ===== */}
          <div className="space-y-6">
            {/* --- Account Info --- */}
            <section className="ui-section-card">
              <div className="ui-section-card__title-row">
                <h2 className="ui-section-card__header-title">Account Information</h2>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="md:col-span-2">
                  <label className="ui-form-label">
                    Display Name *
                  </label>
                  <input
                    type="text"
                    required
                    value={displayName}
                    onChange={(e) => setDisplayName(e.target.value)}
                    className={inputClass}
                    style={inputStyle}
                  />
                </div>
                <div>
                  <label className="ui-form-label">
                    Email *
                  </label>
                  <input
                    type="email"
                    required
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className={inputClass}
                    style={inputStyle}
                  />
                </div>
                <div>
                  <label className="ui-form-label">
                    Phone Number
                  </label>
                  <input
                    type="text"
                    value={phoneNumber}
                    onChange={(e) => setPhoneNumber(e.target.value)}
                    placeholder="e.g. +1234567890"
                    className={inputClass}
                    style={inputStyle}
                  />
                </div>
                <div>
                  <label className="ui-form-label">
                    UID
                  </label>
                  <input
                    type="text"
                    value={uid}
                    onChange={(e) => setUid(e.target.value)}
                    className={inputClass}
                    style={isEdit ? { ...inputStyle, opacity: 0.5 } : inputStyle}
                    disabled={isEdit}
                  />
                </div>
                <div>
                  <label className="ui-form-label">Status</label>
                  <div style={{ display: "flex", borderRadius: 6, overflow: "hidden", border: "1px solid var(--border-input)" }}>
                    {[
                      { value: "active",  label: "Active",  activeColor: "#31ee76", activeBg: "#14532d" },
                      { value: "blocked", label: "Blocked", activeColor: "#f34b4b", activeBg: "#3b1a1a" },
                    ].map((opt, idx) => {
                      const isActive = status === opt.value;
                      return (
                        <button
                          key={opt.value}
                          type="button"
                          onClick={() => setStatus(opt.value)}
                          style={{
                            flex: 1, padding: "8px 0", fontSize: 13, fontWeight: 600,
                            border: "none", cursor: "pointer",
                            backgroundColor: isActive ? opt.activeBg : "var(--bg-input)",
                            color: isActive ? opt.activeColor : "var(--text-secondary)",
                            borderRight: idx === 0 ? "1px solid var(--border-input)" : "none",
                            transition: "background-color 0.15s",
                          }}
                        >
                          {opt.label}
                        </button>
                      );
                    })}
                  </div>
                </div>
              </div>
            </section>

            {/* --- Profile --- */}
            <section className="ui-section-card">
              <div className="ui-section-card__title-row">
                <h2 className="ui-section-card__header-title">Profile</h2>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="ui-form-label">
                    Title
                  </label>
                  <input
                    type="text"
                    value={userTitle}
                    onChange={(e) => setUserTitle(e.target.value)}
                    placeholder="e.g. Church Administrator"
                    className={inputClass}
                    style={inputStyle}
                  />
                </div>
                <div>
                  <label className="ui-form-label">
                    Photo URL
                  </label>
                  <input
                    type="text"
                    value={photoUrl}
                    onChange={(e) => setPhotoUrl(e.target.value)}
                    className={inputClass}
                    style={inputStyle}
                  />
                </div>
                <div className="md:col-span-2">
                  <label className="ui-form-label">
                    Bio
                  </label>
                  <textarea
                    value={bio}
                    onChange={(e) => setBio(e.target.value)}
                    rows={3}
                    className={inputClass}
                    style={{ ...inputStyle, resize: "vertical" }}
                  />
                </div>
              </div>
            </section>
          </div>

          {/* ===== Right Column ===== */}
          <div className="space-y-6">
            {/* --- Security --- */}
            <section className="ui-section-card">
              <div className="ui-section-card__title-row">
                <h2 className="ui-section-card__header-title">Security</h2>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="ui-form-label">
                    Settings PIN
                  </label>
                  <input
                    type="text"
                    inputMode="numeric"
                    value={settingsPIN}
                    onChange={(e) => setSettingsPIN(e.target.value.replace(/\D/g, ""))}
                    placeholder="e.g. 1234"
                    className={inputClass}
                    style={inputStyle}
                  />
                </div>
                <div>
                  <label className="ui-form-label">
                    Quick Settings PIN
                  </label>
                  <input
                    type="text"
                    inputMode="numeric"
                    value={quickSettingsPIN}
                    onChange={(e) => setQuickSettingsPIN(e.target.value.replace(/\D/g, ""))}
                    placeholder="e.g. 0000"
                    className={inputClass}
                    style={inputStyle}
                  />
                </div>
              </div>
            </section>
          </div>
        </div>
      </form>
    </div>
  );
}
