"use client";

import { useState } from "react";
import { UserPlus, Lock, Unlock } from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";

export interface StaffMember {
  id: string;
  name: string;
  email: string;
  username: string;
  role: string;
  isActive: boolean;
  lastLoginAt: string | null;
  createdAt: string;
}

interface CurrentUser {
  id: string;
  role: string;
}

export interface StaffManagementClientProps {
  /**
   * Pre-fetched staff list from server component.
   */
  initialStaff: StaffMember[];
  /**
   * Current logged-in user info.
   */
  currentUser: CurrentUser;
}

export default function StaffManagementClient({
  initialStaff,
  currentUser,
}: StaffManagementClientProps) {
  const [staff, setStaff] = useState<StaffMember[]>(initialStaff);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showResetPassword, setShowResetPassword] = useState<string | null>(
    null,
  );

  const fetchStaff = async () => {
    try {
      const response = await fetch("/api/staff/dashboard/staff");
      if (response.ok) {
        const data = await response.json();
        setStaff(data.staff);
      }
    } catch (error) {
      console.error("Failed to fetch staff:", error);
    }
  };

  const handleToggleActive = async (staffId: string, isActive: boolean) => {
    try {
      const response = await fetchWithCSRF("/api/staff/dashboard/staff/toggle", {
        method: "POST",
        body: JSON.stringify({ staffId, isActive: !isActive }),
      });

      if (response.ok) {
        fetchStaff();
      }
    } catch (error) {
      console.error("Failed to toggle staff status:", error);
    }
  };

  const getRoleBadge = (role: string) => {
    const styles: Record<string, string> = {
      STAFF: "bg-blue-100 text-blue-800",
      ADMIN: "bg-purple-100 text-purple-800",
      SUPER_ADMIN: "bg-red-100 text-red-800",
    };

    return (
      <span
        className={`px-2 py-1 rounded-full text-xs font-semibold ${styles[role]}`}
      >
        {role.replace("_", " ")}
      </span>
    );
  };

  return (
    <div className="space-y-6">
      {/* Action Bar */}
      <div className="flex justify-end">
        <button
          onClick={() => setShowCreateModal(true)}
          className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-green-700"
        >
          <UserPlus className="w-4 h-4" />
          Add Staff Member
        </button>
      </div>

      {/* Staff List */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 border-b border-gray-200">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                  Staff Member
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                  Username
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                  Role
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                  Status
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                  Last Login
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {staff.map((member) => (
                <tr key={member.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4">
                    <div>
                      <p className="text-sm font-medium text-brand-ink">
                        {member.name}
                      </p>
                      <p className="text-xs text-gray-500">{member.email}</p>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <p className="text-sm text-gray-900">{member.username}</p>
                  </td>
                  <td className="px-6 py-4">{getRoleBadge(member.role)}</td>
                  <td className="px-6 py-4">
                    <span
                      className={`px-2 py-1 rounded-full text-xs font-semibold ${
                        member.isActive
                          ? "bg-green-100 text-green-800"
                          : "bg-red-100 text-red-800"
                      }`}
                    >
                      {member.isActive ? "Active" : "Inactive"}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <p className="text-sm text-gray-900">
                      {member.lastLoginAt
                        ? new Date(member.lastLoginAt).toLocaleDateString()
                        : "Never"}
                    </p>
                  </td>
                  <td className="px-6 py-4 text-right">
                    {member.id !== currentUser.id && (
                      <div className="flex gap-2 justify-end">
                        <button
                          onClick={() => setShowResetPassword(member.id)}
                          className="px-3 py-1 rounded-lg text-xs font-medium bg-blue-100 text-blue-700 hover:bg-blue-200"
                        >
                          Reset Password
                        </button>
                        <button
                          onClick={() =>
                            handleToggleActive(member.id, member.isActive)
                          }
                          className={`px-3 py-1 rounded-lg text-xs font-medium ${
                            member.isActive
                              ? "bg-red-100 text-red-700 hover:bg-red-200"
                              : "bg-green-100 text-green-700 hover:bg-green-200"
                          }`}
                        >
                          {member.isActive ? (
                            <>
                              <Lock className="w-3 h-3 inline mr-1" />
                              Deactivate
                            </>
                          ) : (
                            <>
                              <Unlock className="w-3 h-3 inline mr-1" />
                              Activate
                            </>
                          )}
                        </button>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Create Staff Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-md w-full p-6">
            <h3 className="text-xl font-bold text-brand-ink mb-4">
              Add Staff Member
            </h3>
            <form
              onSubmit={async (e) => {
                e.preventDefault();
                const formData = new FormData(e.currentTarget);
                const data = {
                  name: formData.get("name"),
                  email: formData.get("email"),
                  username: formData.get("username"),
                  password: formData.get("password"),
                  role: formData.get("role"),
                };

                try {
                  const response = await fetch(
                    "/api/staff/dashboard/staff/create",
                    {
                      method: "POST",
                      headers: { "Content-Type": "application/json" },
                      body: JSON.stringify(data),
                    },
                  );

                  if (response.ok) {
                    setShowCreateModal(false);
                    fetchStaff();
                  } else {
                    const error = await response.json();
                    alert(error.error || "Failed to create staff member");
                  }
                } catch {
                  alert("Failed to create staff member");
                }
              }}
              className="space-y-4"
            >
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Name
                </label>
                <input
                  type="text"
                  name="name"
                  required
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Email
                </label>
                <input
                  type="email"
                  name="email"
                  required
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Username
                </label>
                <input
                  type="text"
                  name="username"
                  required
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Password
                </label>
                <input
                  type="password"
                  name="password"
                  required
                  minLength={12}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Role
                </label>
                <select
                  name="role"
                  required
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                >
                  <option value="STAFF">Staff</option>
                  <option value="ADMIN">Admin</option>
                  <option value="SUPER_ADMIN">Super Admin</option>
                </select>
              </div>

              <div className="flex gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setShowCreateModal(false)}
                  className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-green-700"
                >
                  Create
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Reset Password Modal (Super Admin) */}
      {showResetPassword && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-xl max-w-md w-full p-6">
            <h3 className="text-2xl font-bold text-brand-ink mb-2">
              Reset User Password
            </h3>
            <p className="text-sm text-gray-600 mb-6">
              As super admin, you can set a new password for this user
            </p>
            <form
              onSubmit={async (e) => {
                e.preventDefault();
                const formData = new FormData(e.currentTarget);
                const newPassword = formData.get("newPassword") as string;
                const confirmPassword = formData.get(
                  "confirmPassword",
                ) as string;

                if (newPassword !== confirmPassword) {
                  alert("Passwords do not match");
                  return;
                }

                try {
                  const response = await fetch(
                    "/api/staff/auth/change-password",
                    {
                      method: "POST",
                      headers: { "Content-Type": "application/json" },
                      body: JSON.stringify({
                        userId: showResetPassword,
                        newPassword,
                      }),
                    },
                  );

                  const data = await response.json();

                  if (response.ok) {
                    alert("Password reset successfully!");
                    setShowResetPassword(null);
                  } else {
                    alert(data.error || "Failed to reset password");
                  }
                } catch {
                  alert("An error occurred. Please try again.");
                }
              }}
            >
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">
                    New Password
                  </label>
                  <input
                    type="password"
                    name="newPassword"
                    required
                    minLength={12}
                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green"
                    placeholder="Min 12 characters"
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    Must include uppercase, lowercase, and numbers
                  </p>
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">
                    Confirm New Password
                  </label>
                  <input
                    type="password"
                    name="confirmPassword"
                    required
                    minLength={12}
                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green"
                    placeholder="Re-enter new password"
                  />
                </div>
              </div>
              <div className="flex gap-3 mt-6">
                <button
                  type="button"
                  onClick={() => setShowResetPassword(null)}
                  className="flex-1 px-4 py-3 border-2 border-gray-300 text-gray-700 font-semibold rounded-lg hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 px-4 py-3 bg-brand-green text-white font-semibold rounded-lg hover:bg-green-700"
                >
                  Reset Password
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
