"use client";

import { useEffect, useState } from "react";
import { getCurrentUser, updateProfile, User } from "@/lib/api";
import { User as UserIcon, Upload } from "lucide-react";

export function ProfileTab() {
  const [user, setUser] = useState<User | null>(null);
  const [name, setName] = useState("");
  const [displayName, setDisplayName] = useState("");
  const [bio, setBio] = useState("");
  const [avatarUrl, setAvatarUrl] = useState("");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [msg, setMsg] = useState("");

  useEffect(() => {
    getCurrentUser()
      .then((u) => {
        setUser(u);
        setName(u.name || "");
        setDisplayName(u.display_name || u.displayName || "");
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  const handleSave = () => {
    setSaving(true);
    setMsg("");
    updateProfile({
      name: name || undefined,
      display_name: displayName || undefined,
      bio: bio || undefined,
      avatar_url: avatarUrl || undefined,
    })
      .then((updated) => {
        setUser(updated);
        setMsg("Profile updated successfully!");
        setTimeout(() => setMsg(""), 3000);
      })
      .catch((e) => setMsg(`Error: ${e.message}`))
      .finally(() => setSaving(false));
  };

  if (loading) {
    return <div className="text-sm text-gray-400 animate-pulse">Loading profile...</div>;
  }

  const initial = (name || user?.email || "U")[0].toUpperCase();

  return (
    <div className="space-y-6">
      {msg && (
        <div className={`p-3 rounded-md text-sm ${msg.includes("Error") ? "bg-red-50 border border-red-200 text-red-700" : "bg-green-50 border border-green-200 text-green-700"}`}>
          {msg}
        </div>
      )}

      {/* Avatar */}
      <div className="flex items-center gap-4">
        {avatarUrl ? (
          <img src={avatarUrl} alt="Avatar" className="w-16 h-16 rounded-md object-cover" />
        ) : (
          <div className="w-16 h-16 rounded-md bg-slack-purple text-white flex items-center justify-center text-2xl font-bold">
            {initial}
          </div>
        )}
        <div>
          <div className="flex items-center gap-2">
            <input
              type="text"
              value={avatarUrl}
              onChange={(e) => setAvatarUrl(e.target.value)}
              placeholder="Avatar URL"
              className="px-2 py-1 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple text-xs"
            />
          </div>
          <p className="text-xs text-gray-400 mt-1">Enter a URL for your avatar image</p>
        </div>
      </div>

      {/* Full name */}
      <div>
        <label className="block text-sm font-semibold text-gray-700 mb-1">Full name</label>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          className="w-full px-3 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple focus:border-transparent text-sm"
        />
      </div>

      {/* Display name */}
      <div>
        <label className="block text-sm font-semibold text-gray-700 mb-1">
          Display name <span className="text-gray-400 font-normal">(optional)</span>
        </label>
        <input
          type="text"
          value={displayName}
          onChange={(e) => setDisplayName(e.target.value)}
          placeholder="The name everyone sees"
          className="w-full px-3 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple focus:border-transparent text-sm"
        />
      </div>

      {/* Bio */}
      <div>
        <label className="block text-sm font-semibold text-gray-700 mb-1">
          What I do <span className="text-gray-400 font-normal">(optional)</span>
        </label>
        <textarea
          value={bio}
          onChange={(e) => setBio(e.target.value)}
          placeholder="Tell your team what you do"
          rows={3}
          className="w-full px-3 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple focus:border-transparent text-sm resize-none"
        />
      </div>

      {/* Save */}
      <div className="flex justify-end">
        <button
          onClick={handleSave}
          disabled={saving}
          className="flex items-center gap-1.5 px-6 py-2.5 rounded-md bg-slack-purple text-white font-semibold text-sm hover:bg-slack-darkpurple transition-colors disabled:opacity-50"
        >
          <Upload size={14} />
          {saving ? "Saving..." : "Save changes"}
        </button>
      </div>
    </div>
  );
}