import { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import {
  Music,
  Users,
  ListMusic,
  Download,
  Upload,
  Settings,
  UserPlus,
  Trash2,
  Edit,
  X,
  Check,
  AlertCircle,
  Fingerprint,
  Eye,
  EyeOff,
} from "lucide-react";
import api from "@utils/api";
import { useTheme } from "@context/ThemeContext";
import { useStats, useDataMutations } from "@hooks/useDataFetch";
import {
  isBiometricAvailable,
  registerBiometric,
  storeBiometricCredential,
} from "@utils/biometric";
import toast from "react-hot-toast";

export default function AdminPage() {
  const { isDark } = useTheme();
  const navigate = useNavigate();
  const fileInputRef = useRef(null);

  // Use cached stats from global store
  const { stats, refetch: refetchStats } = useStats();
  const { invalidateAll } = useDataMutations();

  const [users, setUsers] = useState([]);
  const [showUserModal, setShowUserModal] = useState(false);
  const [showImportModal, setShowImportModal] = useState(false);
  const [editingUser, setEditingUser] = useState(null);
  const [notification, setNotification] = useState(null);
  const [isExporting, setIsExporting] = useState(false);
  const [isImporting, setIsImporting] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [userForm, setUserForm] = useState({
    username: "",
    password: "",
    role: "user",
    biometric_enabled: false,
  });

  // 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 inputBg = isDark
    ? "bg-white/10 border-white/20 text-white placeholder-white/50"
    : "bg-white border-gray-300 text-gray-900 placeholder-gray-400";

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    try {
      const response = await api.get("/admin/users");
      if (response.data.success) {
        setUsers(response.data.users);
      }
    } catch (err) {
      console.error("Failed to fetch users:", err);
    }
  };

  const showNotification = (message, type = "success") => {
    setNotification({ message, type });
    setTimeout(() => setNotification(null), 4000);
  };

  // Export functions
  const handleExport = async (type) => {
    setIsExporting(true);
    try {
      const response = await api.get(`/admin/export/${type}`, {
        responseType: "blob",
      });

      const blob = new Blob([response.data], { type: "application/json" });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `${type}-export-${new Date().toISOString().split("T")[0]}.json`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      showNotification(`Successfully exported ${type}`, "success");
    } catch (err) {
      console.error("Export error:", err);
      showNotification(`Failed to export ${type}`, "error");
    } finally {
      setIsExporting(false);
    }
  };

  // Import functions
  const handleImportClick = () => {
    setShowImportModal(true);
  };

  const handleFileSelect = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    setIsImporting(true);
    const formData = new FormData();
    formData.append("file", file);

    try {
      const response = await api.post("/admin/import/songs", formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });

      if (response.data.success) {
        showNotification(response.data.message, "success");
        fetchStats();
      } else {
        showNotification(response.data.message || "Import failed", "error");
      }
    } catch (err) {
      console.error("Import error:", err);
      showNotification(
        "Failed to import songs: " +
          (err.response?.data?.message || err.message),
        "error",
      );
    } finally {
      setIsImporting(false);
      setShowImportModal(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };

  // User management functions
  const handleCreateUser = () => {
    setEditingUser(null);
    setUserForm({
      username: "",
      password: "",
      role: "user",
      biometric_enabled: false,
    });
    setShowUserModal(true);
  };

  const handleEditUser = (user) => {
    setEditingUser(user);
    setUserForm({
      username: user.username,
      password: "",
      role: user.role,
      biometric_enabled: user.biometric_enabled || false,
    });
    setShowUserModal(true);
  };

  const handleSaveUser = async () => {
    try {
      if (editingUser) {
        const updates = { ...userForm };
        if (!updates.password) delete updates.password;

        const response = await api.put(
          `/admin/users/${editingUser.id}`,
          updates,
        );
        if (response.data.success) {
          showNotification("User updated successfully", "success");
        }
      } else {
        if (!userForm.username || !userForm.password) {
          showNotification("Username and password are required", "error");
          return;
        }
        const response = await api.post("/admin/users", userForm);
        if (response.data.success) {
          showNotification("User created successfully", "success");
        }
      }
      fetchUsers();
      setShowUserModal(false);
    } catch (err) {
      console.error("Save user error:", err);
      showNotification(
        err.response?.data?.message || "Failed to save user",
        "error",
      );
    }
  };

  const handleDeleteUser = async (user) => {
    if (!confirm(`Are you sure you want to delete user "${user.username}"?`))
      return;

    try {
      const response = await api.delete(`/admin/users/${user.id}`);
      if (response.data.success) {
        showNotification("User deleted successfully", "success");
        fetchUsers();
      }
    } catch (err) {
      console.error("Delete user error:", err);
      showNotification("Failed to delete user", "error");
    }
  };

  const handleToggleBiometric = async (user) => {
    if (!user.biometric_enabled) {
      // Enabling biometric - need to register
      const available = await isBiometricAvailable();
      if (!available) {
        showNotification(
          "Biometric authentication not available on this device",
          "error",
        );
        return;
      }

      try {
        showNotification(
          "Please authenticate with your device biometric...",
          "info",
        );

        // Register biometric credential
        const credentialData = await registerBiometric(user.username, user.id);

        // Send to backend
        const response = await api.post(`/auth/biometric-register`, {
          username: user.username,
          credentialId: credentialData.id,
          publicKey: credentialData.response.attestationObject,
        });

        if (response.data.success) {
          // Store credential ID locally
          storeBiometricCredential(user.username, credentialData.id);

          showNotification(
            `Biometric authentication enabled for ${user.username}`,
            "success",
          );
          fetchUsers();
        }
      } catch (err) {
        console.error("Biometric registration error:", err);
        showNotification(
          err.message || "Failed to register biometric",
          "error",
        );
      }
    } else {
      // Disabling biometric
      try {
        const response = await api.post(`/admin/users/${user.id}/biometric`, {
          enable: false,
        });
        if (response.data.success) {
          showNotification(
            `Biometric disabled for ${user.username}`,
            "success",
          );
          fetchUsers();
        }
      } catch (err) {
        console.error("Biometric disable error:", err);
        showNotification("Failed to disable biometric", "error");
      }
    }
  };

  return (
    <div className="space-y-6">
      {/* Notification */}
      {notification && (
        <div
          className={`fixed top-4 right-4 z-50 px-6 py-3 rounded-xl shadow-lg flex items-center gap-3 animate-slide-in ${
            notification.type === "success"
              ? "bg-emerald-500 text-white"
              : "bg-red-500 text-white"
          }`}
        >
          {notification.type === "success" ? (
            <Check size={20} />
          ) : (
            <AlertCircle size={20} />
          )}
          {notification.message}
        </div>
      )}

      <h1 className={`text-3xl font-bold ${textPrimary}`}>Admin Dashboard</h1>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className={`backdrop-blur-lg rounded-xl p-6 border ${bgCard}`}>
          <div className="flex items-center gap-3 mb-2">
            <div
              className={`w-10 h-10 rounded-lg flex items-center justify-center ${isDark ? "bg-cyan-500/20" : "bg-cyan-100"}`}
            >
              <Music size={20} className="text-cyan-500" />
            </div>
            <h3 className={`text-sm ${textMuted}`}>Total Songs</h3>
          </div>
          <p className={`text-3xl font-bold ${textPrimary}`}>{stats.songs}</p>
        </div>
        <div className={`backdrop-blur-lg rounded-xl p-6 border ${bgCard}`}>
          <div className="flex items-center gap-3 mb-2">
            <div
              className={`w-10 h-10 rounded-lg flex items-center justify-center ${isDark ? "bg-violet-500/20" : "bg-violet-100"}`}
            >
              <Users size={20} className="text-violet-500" />
            </div>
            <h3 className={`text-sm ${textMuted}`}>Profiles</h3>
          </div>
          <p className={`text-3xl font-bold ${textPrimary}`}>
            {stats.profiles}
          </p>
        </div>
        <div className={`backdrop-blur-lg rounded-xl p-6 border ${bgCard}`}>
          <div className="flex items-center gap-3 mb-2">
            <div
              className={`w-10 h-10 rounded-lg flex items-center justify-center ${isDark ? "bg-amber-500/20" : "bg-amber-100"}`}
            >
              <ListMusic size={20} className="text-amber-500" />
            </div>
            <h3 className={`text-sm ${textMuted}`}>Worship Lists</h3>
          </div>
          <p className={`text-3xl font-bold ${textPrimary}`}>{stats.lists}</p>
        </div>
      </div>

      {/* Admin Actions */}
      <div className={`backdrop-blur-lg rounded-xl p-6 border ${bgCard}`}>
        <h2 className={`text-xl font-semibold ${textPrimary} mb-4`}>
          Quick Actions
        </h2>
        <div className="grid md:grid-cols-2 gap-4">
          {/* Export Data */}
          <div className="relative">
            <button
              onClick={() => handleExport("all")}
              disabled={isExporting}
              className={`w-full p-4 rounded-xl text-left transition-all flex items-start gap-4 ${
                isDark
                  ? "bg-blue-500/20 hover:bg-blue-500/30 border border-blue-400/30"
                  : "bg-blue-50 hover:bg-blue-100 border border-blue-200"
              } ${isExporting ? "opacity-50 cursor-not-allowed" : ""}`}
            >
              <div
                className={`w-12 h-12 rounded-xl flex items-center justify-center ${isDark ? "bg-blue-500/30" : "bg-blue-200"}`}
              >
                <Download size={24} className="text-blue-500" />
              </div>
              <div>
                <h4 className={`font-medium ${textPrimary}`}>
                  {isExporting ? "Exporting..." : "Export Data"}
                </h4>
                <p className={`text-sm ${textMuted}`}>
                  Download full database backup
                </p>
              </div>
            </button>
            <div className="mt-2 flex gap-2 flex-wrap">
              <button
                onClick={() => handleExport("songs")}
                className={`text-xs px-3 py-1.5 rounded-lg ${
                  isDark
                    ? "bg-blue-500/10 text-blue-300 hover:bg-blue-500/20"
                    : "bg-blue-100 text-blue-700 hover:bg-blue-200"
                }`}
              >
                Songs Only
              </button>
              <button
                onClick={() => handleExport("profiles")}
                className={`text-xs px-3 py-1.5 rounded-lg ${
                  isDark
                    ? "bg-blue-500/10 text-blue-300 hover:bg-blue-500/20"
                    : "bg-blue-100 text-blue-700 hover:bg-blue-200"
                }`}
              >
                Profiles Only
              </button>
              <button
                onClick={() => handleExport("lists")}
                className={`text-xs px-3 py-1.5 rounded-lg ${
                  isDark
                    ? "bg-blue-500/10 text-blue-300 hover:bg-blue-500/20"
                    : "bg-blue-100 text-blue-700 hover:bg-blue-200"
                }`}
              >
                Lists Only
              </button>
            </div>
          </div>

          {/* Import Songs */}
          <button
            onClick={handleImportClick}
            disabled={isImporting}
            className={`p-4 rounded-xl text-left transition-all flex items-start gap-4 ${
              isDark
                ? "bg-emerald-500/20 hover:bg-emerald-500/30 border border-emerald-400/30"
                : "bg-emerald-50 hover:bg-emerald-100 border border-emerald-200"
            } ${isImporting ? "opacity-50 cursor-not-allowed" : ""}`}
          >
            <div
              className={`w-12 h-12 rounded-xl flex items-center justify-center ${isDark ? "bg-emerald-500/30" : "bg-emerald-200"}`}
            >
              <Upload size={24} className="text-emerald-500" />
            </div>
            <div>
              <h4 className={`font-medium ${textPrimary}`}>
                {isImporting ? "Importing..." : "Import Songs"}
              </h4>
              <p className={`text-sm ${textMuted}`}>
                Bulk import from JSON file
              </p>
            </div>
          </button>

          {/* Manage Users */}
          <button
            onClick={handleCreateUser}
            className={`p-4 rounded-xl text-left transition-all flex items-start gap-4 ${
              isDark
                ? "bg-violet-500/20 hover:bg-violet-500/30 border border-violet-400/30"
                : "bg-violet-50 hover:bg-violet-100 border border-violet-200"
            }`}
          >
            <div
              className={`w-12 h-12 rounded-xl flex items-center justify-center ${isDark ? "bg-violet-500/30" : "bg-violet-200"}`}
            >
              <UserPlus size={24} className="text-violet-500" />
            </div>
            <div>
              <h4 className={`font-medium ${textPrimary}`}>Add New User</h4>
              <p className={`text-sm ${textMuted}`}>Create new user account</p>
            </div>
          </button>

          {/* System Settings */}
          <button
            onClick={() => navigate("/settings")}
            className={`p-4 rounded-xl text-left transition-all flex items-start gap-4 ${
              isDark
                ? "bg-amber-500/20 hover:bg-amber-500/30 border border-amber-400/30"
                : "bg-amber-50 hover:bg-amber-100 border border-amber-200"
            }`}
          >
            <div
              className={`w-12 h-12 rounded-xl flex items-center justify-center ${isDark ? "bg-amber-500/30" : "bg-amber-200"}`}
            >
              <Settings size={24} className="text-amber-500" />
            </div>
            <div>
              <h4 className={`font-medium ${textPrimary}`}>System Settings</h4>
              <p className={`text-sm ${textMuted}`}>Configure system options</p>
            </div>
          </button>
        </div>
      </div>

      {/* User List */}
      {users.length > 0 && (
        <div className={`backdrop-blur-lg rounded-xl p-6 border ${bgCard}`}>
          <h2 className={`text-xl font-semibold ${textPrimary} mb-4`}>
            User Accounts
          </h2>
          <div className="space-y-3">
            {users.map((user) => (
              <div
                key={user.id}
                className={`flex items-center justify-between p-4 rounded-xl ${
                  isDark ? "bg-white/5" : "bg-gray-50"
                }`}
              >
                <div className="flex items-center gap-4">
                  <div
                    className={`w-10 h-10 rounded-full flex items-center justify-center ${
                      isDark ? "bg-violet-500/20" : "bg-violet-100"
                    }`}
                  >
                    <Users size={18} className="text-violet-500" />
                  </div>
                  <div>
                    <p className={`font-medium ${textPrimary}`}>
                      {user.username}
                    </p>
                    <div className="flex items-center gap-2">
                      <span
                        className={`text-xs px-2 py-0.5 rounded-full ${
                          user.role === "admin"
                            ? "bg-amber-500/20 text-amber-500"
                            : "bg-cyan-500/20 text-cyan-500"
                        }`}
                      >
                        {user.role}
                      </span>
                      {user.biometric_enabled && (
                        <span className="text-xs px-2 py-0.5 rounded-full bg-emerald-500/20 text-emerald-500 flex items-center gap-1">
                          <Fingerprint size={12} />
                          Biometric
                        </span>
                      )}
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => handleToggleBiometric(user)}
                    className={`p-2.5 sm:p-2 rounded-lg touch-manipulation ${
                      isDark ? "hover:bg-white/10" : "hover:bg-gray-200"
                    }`}
                    title={
                      user.biometric_enabled
                        ? "Disable biometric"
                        : "Enable biometric"
                    }
                  >
                    <Fingerprint
                      size={20}
                      className={
                        user.biometric_enabled ? "text-emerald-500" : textMuted
                      }
                    />
                  </button>
                  <button
                    onClick={() => handleEditUser(user)}
                    className={`p-2.5 sm:p-2 rounded-lg touch-manipulation ${isDark ? "hover:bg-white/10" : "hover:bg-gray-200"}`}
                  >
                    <Edit size={20} className={textSecondary} />
                  </button>
                  <button
                    onClick={() => handleDeleteUser(user)}
                    className={`p-2.5 sm:p-2 rounded-lg touch-manipulation ${isDark ? "hover:bg-red-500/20" : "hover:bg-red-100"}`}
                  >
                    <Trash2 size={20} className="text-red-500" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Hidden file input */}
      <input
        ref={fileInputRef}
        type="file"
        accept=".json"
        onChange={handleFileSelect}
        className="hidden"
      />

      {/* Import Modal */}
      {showImportModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
          <div
            className={`w-full max-w-md mx-4 rounded-2xl p-6 ${
              isDark ? "bg-slate-800" : "bg-white"
            }`}
          >
            <div className="flex items-center justify-between mb-4">
              <h3 className={`text-xl font-semibold ${textPrimary}`}>
                Import Songs
              </h3>
              <button
                onClick={() => setShowImportModal(false)}
                className={`p-2 rounded-lg ${isDark ? "hover:bg-white/10" : "hover:bg-gray-100"}`}
              >
                <X size={20} className={textSecondary} />
              </button>
            </div>
            <p className={`mb-4 ${textSecondary}`}>
              Select a JSON file containing song data. The file should have an
              array of songs with title, artist, lyrics, and other fields.
            </p>
            <div
              className={`border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-colors ${
                isDark
                  ? "border-white/20 hover:border-emerald-400/50 hover:bg-emerald-500/10"
                  : "border-gray-300 hover:border-emerald-400 hover:bg-emerald-50"
              }`}
              onClick={() => fileInputRef.current?.click()}
            >
              <Upload size={40} className={`mx-auto mb-3 ${textMuted}`} />
              <p className={textPrimary}>Click to select file</p>
              <p className={`text-sm ${textMuted}`}>or drag and drop</p>
            </div>
          </div>
        </div>
      )}

      {/* User Modal */}
      {showUserModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
          <div
            className={`w-full max-w-md mx-4 rounded-2xl p-6 ${
              isDark ? "bg-slate-800" : "bg-white"
            }`}
          >
            <div className="flex items-center justify-between mb-4">
              <h3 className={`text-xl font-semibold ${textPrimary}`}>
                {editingUser ? "Edit User" : "Create New User"}
              </h3>
              <button
                onClick={() => setShowUserModal(false)}
                className={`p-2 rounded-lg ${isDark ? "hover:bg-white/10" : "hover:bg-gray-100"}`}
              >
                <X size={20} className={textSecondary} />
              </button>
            </div>

            <div className="space-y-4">
              <div>
                <label
                  className={`block text-sm font-medium mb-1 ${textSecondary}`}
                >
                  Username
                </label>
                <input
                  type="text"
                  value={userForm.username}
                  onChange={(e) =>
                    setUserForm({ ...userForm, username: e.target.value })
                  }
                  className={`w-full px-4 py-2 rounded-lg border ${inputBg} focus:outline-none focus:ring-2 focus:ring-violet-500`}
                  placeholder="Enter username"
                />
              </div>

              <div>
                <label
                  className={`block text-sm font-medium mb-1 ${textSecondary}`}
                >
                  Password {editingUser && "(leave blank to keep current)"}
                </label>
                <div className="relative">
                  <input
                    type={showPassword ? "text" : "password"}
                    value={userForm.password}
                    onChange={(e) =>
                      setUserForm({ ...userForm, password: e.target.value })
                    }
                    className={`w-full px-4 py-2 pr-10 rounded-lg border ${inputBg} focus:outline-none focus:ring-2 focus:ring-violet-500`}
                    placeholder="Enter password"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className={`absolute right-3 top-1/2 -translate-y-1/2 ${textMuted}`}
                  >
                    {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                  </button>
                </div>
              </div>

              <div>
                <label
                  className={`block text-sm font-medium mb-1 ${textSecondary}`}
                >
                  Role
                </label>
                <select
                  value={userForm.role}
                  onChange={(e) =>
                    setUserForm({ ...userForm, role: e.target.value })
                  }
                  className={`w-full px-4 py-2 rounded-lg border ${inputBg} focus:outline-none focus:ring-2 focus:ring-violet-500`}
                >
                  <option value="user">User</option>
                  <option value="admin">Admin</option>
                </select>
              </div>

              <div className="flex items-center gap-3">
                <button
                  onClick={() =>
                    setUserForm({
                      ...userForm,
                      biometric_enabled: !userForm.biometric_enabled,
                    })
                  }
                  className={`relative w-12 h-7 rounded-full transition-colors ${
                    userForm.biometric_enabled
                      ? "bg-emerald-500"
                      : isDark
                        ? "bg-white/20"
                        : "bg-gray-300"
                  }`}
                >
                  <div
                    className={`absolute top-1 w-5 h-5 bg-white rounded-full shadow-md transition-transform ${
                      userForm.biometric_enabled ? "left-6" : "left-1"
                    }`}
                  />
                </button>
                <span className={textSecondary}>
                  <Fingerprint size={16} className="inline mr-1" />
                  Enable Biometric Authentication
                </span>
              </div>
            </div>

            <div className="flex gap-3 mt-6">
              <button
                onClick={() => setShowUserModal(false)}
                className={`flex-1 py-2 px-4 rounded-lg font-medium ${
                  isDark
                    ? "bg-white/10 text-white hover:bg-white/20"
                    : "bg-gray-100 text-gray-700 hover:bg-gray-200"
                }`}
              >
                Cancel
              </button>
              <button
                onClick={handleSaveUser}
                className="flex-1 py-2 px-4 rounded-lg font-medium bg-violet-500 text-white hover:bg-violet-600"
              >
                {editingUser ? "Save Changes" : "Create User"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* CSS for animations */}
      <style>{`
        @keyframes slide-in {
          from {
            transform: translateX(100%);
            opacity: 0;
          }
          to {
            transform: translateX(0);
            opacity: 1;
          }
        }
        .animate-slide-in {
          animation: slide-in 0.3s ease-out;
        }
      `}</style>
    </div>
  );
}
