import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Music, User, Mail, Key, Plus, Trash2, X } from "lucide-react";
import api from "@utils/api";
import { useTheme } from "@context/ThemeContext";
import { useProfiles, useDataMutations } from "@hooks/useDataFetch";

export default function ProfilesPage() {
  const navigate = useNavigate();
  const { isDark } = useTheme();

  // Use cached data from global store
  const {
    profiles,
    loading: profilesLoading,
    refetch: refetchProfiles,
  } = useProfiles();
  const { invalidateProfiles } = useDataMutations();

  const [selectedProfile, setSelectedProfile] = useState(null);
  const [profileSongs, setProfileSongs] = useState([]);
  const [showAddModal, setShowAddModal] = useState(false);
  const [newProfile, setNewProfile] = useState({
    name: "",
    email: "",
    default_key: "C",
  });
  const [deleting, setDeleting] = useState(false);
  const [loading, setLoading] = useState(true);

  // Update loading state based on cache
  useEffect(() => {
    if (!profilesLoading) {
      setLoading(false);
    }
  }, [profilesLoading]);

  // Theme-aware classes
  const textPrimary = isDark ? "text-white" : "text-gray-900";
  const textSecondary = isDark ? "text-white/70" : "text-gray-600";
  const textMuted = isDark ? "text-white/50" : "text-gray-500";
  const bgCard = isDark
    ? "bg-white/10 border-white/20"
    : "bg-white border-gray-200 shadow-sm";
  const bgCardHover = isDark ? "hover:bg-white/15" : "hover:bg-gray-50";
  const bgSongItem = isDark ? "bg-white/5" : "bg-gray-50";

  const handleSelectProfile = async (profile) => {
    setSelectedProfile(profile);
    try {
      const response = await api.get(`/profiles/${profile.id}`);
      if (response.data.success) {
        setProfileSongs(response.data.songs || []);
      }
    } catch (err) {
      console.error("Failed to fetch profile songs:", err);
      setProfileSongs([]);
    }
  };

  const handleAddProfile = async () => {
    if (!newProfile.name.trim()) {
      alert("Profile name is required");
      return;
    }

    try {
      const response = await api.post("/profiles", newProfile);
      if (response.data.success) {
        // Invalidate cache and refetch
        invalidateProfiles();
        refetchProfiles();
        setShowAddModal(false);
        setNewProfile({ name: "", email: "", default_key: "C" });
      }
    } catch (err) {
      console.error("Failed to add profile:", err);
      alert("Failed to add profile");
    }
  };

  const handleDeleteProfile = async () => {
    if (!selectedProfile) return;

    if (!confirm(`Are you sure you want to delete ${selectedProfile.name}?`)) {
      return;
    }

    setDeleting(true);
    try {
      const response = await api.delete(`/profiles/${selectedProfile.id}`);
      if (response.data.success) {
        // Invalidate cache and refetch
        invalidateProfiles();
        refetchProfiles();
        setSelectedProfile(null);
        setProfileSongs([]);
      }
    } catch (err) {
      console.error("Failed to delete profile:", err);
      alert("Failed to delete profile");
    } finally {
      setDeleting(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className={`text-xl ${textMuted}`}>Loading profiles...</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className={`text-3xl font-bold ${textPrimary}`}>Band Profiles</h1>
          <p className={textMuted}>{profiles.length} musicians</p>
        </div>
        <div className="flex gap-2">
          {selectedProfile && (
            <button
              onClick={handleDeleteProfile}
              disabled={deleting}
              className="flex items-center gap-2 px-5 py-2.5 bg-red-500 hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium rounded-xl transition-colors"
            >
              <Trash2 size={18} />
              <span>{deleting ? "Deleting..." : "Delete Profile"}</span>
            </button>
          )}
          <button
            onClick={() => setShowAddModal(true)}
            className="flex items-center gap-2 px-5 py-2.5 bg-blue-500 hover:bg-blue-600 text-white font-medium rounded-xl transition-colors"
          >
            <Plus size={18} />
            <span>Add Profile</span>
          </button>
        </div>
      </div>

      <div className="grid lg:grid-cols-3 gap-6">
        {/* Profiles List */}
        <div className="lg:col-span-1 space-y-3">
          {profiles.length === 0 ? (
            <div
              className={`backdrop-blur-lg rounded-xl p-6 border text-center ${bgCard}`}
            >
              <User size={40} className={`mx-auto mb-3 ${textMuted}`} />
              <p className={textMuted}>No profiles yet</p>
            </div>
          ) : (
            profiles.map((profile) => (
              <button
                key={profile.id}
                onClick={() => handleSelectProfile(profile)}
                className={`w-full text-left backdrop-blur-lg rounded-xl p-4 
                  border transition-all ${
                    selectedProfile?.id === profile.id
                      ? `border-blue-400 ${isDark ? "bg-blue-500/20" : "bg-blue-50"}`
                      : `${bgCard} ${bgCardHover}`
                  }`}
              >
                <div className="flex items-center space-x-3">
                  <div
                    className="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 
                    rounded-full flex items-center justify-center text-white text-xl font-bold"
                  >
                    {profile.name?.charAt(0)?.toUpperCase() || "?"}
                  </div>
                  <div>
                    <h3 className={`text-lg font-semibold ${textPrimary}`}>
                      {profile.name}
                    </h3>
                    <p className={`text-sm ${textMuted}`}>
                      Key: {profile.default_key || "C"}
                    </p>
                  </div>
                </div>
              </button>
            ))
          )}
        </div>

        {/* Profile Details */}
        <div className="lg:col-span-2">
          {selectedProfile ? (
            <div className={`backdrop-blur-lg rounded-xl p-6 border ${bgCard}`}>
              <div className="flex items-center space-x-4 mb-6">
                <div
                  className="w-20 h-20 bg-gradient-to-br from-blue-500 to-purple-600 
                  rounded-full flex items-center justify-center text-white text-3xl font-bold"
                >
                  {selectedProfile.name?.charAt(0)?.toUpperCase() || "?"}
                </div>
                <div>
                  <h2 className={`text-2xl font-bold ${textPrimary}`}>
                    {selectedProfile.name}
                  </h2>
                  <div className={`flex items-center gap-2 ${textSecondary}`}>
                    <Key size={14} />
                    <span>
                      Default Key: {selectedProfile.default_key || "C"}
                    </span>
                  </div>
                  {selectedProfile.email && (
                    <div
                      className={`flex items-center gap-2 text-sm ${textMuted}`}
                    >
                      <Mail size={12} />
                      <span>{selectedProfile.email}</span>
                    </div>
                  )}
                </div>
              </div>

              {/* Profile's Songs */}
              <div>
                <h3 className={`text-lg font-semibold ${textPrimary} mb-4`}>
                  Assigned Songs ({profileSongs.length})
                </h3>
                {profileSongs.length > 0 ? (
                  <div className="space-y-2 max-h-96 overflow-y-auto">
                    {profileSongs.map((song) => (
                      <div
                        key={song.id}
                        onClick={() => navigate(`/song/${song.id}`)}
                        className={`flex items-center justify-between rounded-lg p-4 cursor-pointer transition-all ${bgSongItem} ${isDark ? "hover:bg-white/10" : "hover:bg-gray-100 hover:shadow-sm"} border ${isDark ? "border-transparent" : "border-gray-200"}`}
                      >
                        <div className="flex items-center gap-3">
                          <div
                            className={`w-10 h-10 rounded-lg flex items-center justify-center ${isDark ? "bg-cyan-500/20" : "bg-cyan-100"}`}
                          >
                            <Music size={18} className="text-cyan-500" />
                          </div>
                          <div>
                            <p
                              className={`font-medium text-base ${textPrimary}`}
                            >
                              {song.title}
                            </p>
                            <p className={`text-sm ${textMuted}`}>
                              {song.artist}
                            </p>
                          </div>
                        </div>
                        <span
                          className={`px-3 py-1 rounded-lg text-sm font-bold ${isDark ? "bg-amber-500/20 text-amber-400" : "bg-amber-100 text-amber-700"}`}
                        >
                          {song.preferred_key ||
                            selectedProfile.default_key ||
                            "C"}
                        </span>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className={textMuted}>No songs assigned to this profile</p>
                )}
              </div>
            </div>
          ) : (
            <div
              className={`backdrop-blur-lg rounded-xl p-12 border flex items-center justify-center ${bgCard}`}
            >
              <div className="text-center">
                <User size={48} className={`mx-auto mb-4 ${textMuted}`} />
                <p className={`text-lg ${textMuted}`}>
                  Select a profile to view details
                </p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Add Profile Modal */}
      {showAddModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div
            className={`max-w-md w-full rounded-xl p-6 ${isDark ? "bg-slate-800 border border-white/10" : "bg-white border border-gray-200"}`}
          >
            <div className="flex justify-between items-center mb-4">
              <h2 className={`text-xl font-bold ${textPrimary}`}>
                Add New Profile
              </h2>
              <button
                onClick={() => {
                  setShowAddModal(false);
                  setNewProfile({ name: "", email: "", default_key: "C" });
                }}
                className={`p-2 rounded-lg ${isDark ? "hover:bg-white/10" : "hover:bg-gray-100"}`}
              >
                <X size={20} className={textMuted} />
              </button>
            </div>

            <div className="space-y-4">
              <div>
                <label
                  className={`block text-sm font-medium mb-2 ${textSecondary}`}
                >
                  Name *
                </label>
                <input
                  type="text"
                  value={newProfile.name}
                  onChange={(e) =>
                    setNewProfile({ ...newProfile, name: e.target.value })
                  }
                  placeholder="Enter profile name"
                  className={`w-full px-4 py-2 rounded-lg border ${isDark ? "bg-white/5 border-white/10 text-white placeholder-white/40" : "bg-white border-gray-200 text-gray-900 placeholder-gray-400"}`}
                />
              </div>

              <div>
                <label
                  className={`block text-sm font-medium mb-2 ${textSecondary}`}
                >
                  Email
                </label>
                <input
                  type="email"
                  value={newProfile.email}
                  onChange={(e) =>
                    setNewProfile({ ...newProfile, email: e.target.value })
                  }
                  placeholder="optional@email.com"
                  className={`w-full px-4 py-2 rounded-lg border ${isDark ? "bg-white/5 border-white/10 text-white placeholder-white/40" : "bg-white border-gray-200 text-gray-900 placeholder-gray-400"}`}
                />
              </div>

              <div>
                <label
                  className={`block text-sm font-medium mb-2 ${textSecondary}`}
                >
                  Default Key
                </label>
                <select
                  value={newProfile.default_key}
                  onChange={(e) =>
                    setNewProfile({
                      ...newProfile,
                      default_key: e.target.value,
                    })
                  }
                  className={`w-full px-4 py-2 rounded-lg border ${isDark ? "bg-white/5 border-white/10 text-white" : "bg-white border-gray-200 text-gray-900"}`}
                >
                  {[
                    "C",
                    "C#",
                    "D",
                    "Eb",
                    "E",
                    "F",
                    "F#",
                    "G",
                    "Ab",
                    "A",
                    "Bb",
                    "B",
                  ].map((key) => (
                    <option key={key} value={key}>
                      {key}
                    </option>
                  ))}
                </select>
              </div>

              <div className="flex gap-2 pt-2">
                <button
                  onClick={() => {
                    setShowAddModal(false);
                    setNewProfile({ name: "", email: "", default_key: "C" });
                  }}
                  className={`flex-1 px-4 py-2 rounded-lg ${isDark ? "bg-white/10 hover:bg-white/20" : "bg-gray-100 hover:bg-gray-200"} ${textPrimary}`}
                >
                  Cancel
                </button>
                <button
                  onClick={handleAddProfile}
                  className="flex-1 px-4 py-2 rounded-lg bg-blue-500 hover:bg-blue-600 text-white font-medium"
                >
                  Add Profile
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
