'use client';

import { useState } from 'react';
import { LayoutShell } from '../../../../components/layout-shell';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import api from '../../../../lib/api-client';
import { UserModal } from '../../../../components/super-admin/users/user-modal';
import { BulkImportUsersModal } from '../../../../components/super-admin/users/bulk-import-users-modal';
import { Edit, RefreshCcw } from 'lucide-react';

export default function UsersPage() {
  const queryClient = useQueryClient();
  const [banner, setBanner] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [mutatingUserId, setMutatingUserId] = useState<number | null>(null);
  const [resettingId, setResettingId] = useState<number | null>(null);
  const [approvingId, setApprovingId] = useState<number | null>(null);
  const [codeInputs, setCodeInputs] = useState<Record<number, string>>({});
  
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<any>(null);

  const [isBulkImportModalOpen, setIsBulkImportModalOpen] = useState(false);

  const { data } = useQuery({
    queryKey: ['users'],
    queryFn: async () => {
      const response = await api.get('/users');
      return response.data;
    },
  });

  const handleCreate = () => {
      setEditingUser(null);
      setIsModalOpen(true);
  };

  const handleEdit = (user: any) => {
      setEditingUser(user);
      setIsModalOpen(true);
  };

  const { data: passwordRequestsData, isLoading: passwordRequestsLoading } = useQuery({
    queryKey: ['password-change-requests'],
    queryFn: async () => {
      const response = await api.get('/password-change-requests');
      return response.data;
    },
  });

  const toggleStatus = useMutation({
    mutationFn: async ({ userId, active }: { userId: number; active: boolean }) => {
      setMutatingUserId(userId);
      await api.patch(`/users/${userId}/status`, { active });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['users'] });
      setBanner({ type: 'success', text: 'User status updated' });
    },
    onError: (error: any) => {
      setBanner({ type: 'error', text: error?.response?.data?.error ?? 'Failed to update user' });
    },
    onSettled: () => {
      setMutatingUserId(null);
    },
  });

  const initiateReset = useMutation({
    mutationFn: async (userId: number) => {
      setResettingId(userId);
      await api.post('/admin/password-reset/initiate', { user_id: userId });
    },
    onSuccess: () => {
      setBanner({ type: 'success', text: 'Password reset email sent to user.' });
    },
    onError: (error: any) => {
      setBanner({ type: 'error', text: error?.response?.data?.error ?? 'Failed to send reset email' });
    },
    onSettled: () => {
      setResettingId(null);
    },
  });

  const approveRequest = useMutation({
    mutationFn: async ({ requestId, code }: { requestId: number; code: string }) => {
      setApprovingId(requestId);
      await api.post(`/password-change-requests/${requestId}/approve`, { code });
    },
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ['password-change-requests'] });
      setBanner({ type: 'success', text: 'Password change approved' });
      setCodeInputs((prev) => ({ ...prev, [variables.requestId]: '' }));
    },
    onError: (error: any) => {
      setBanner({ type: 'error', text: error?.response?.data?.error ?? 'Approval failed' });
    },
    onSettled: () => {
      setApprovingId(null);
    },
  });

  const requests = passwordRequestsData?.data ?? [];

  return (
    <LayoutShell role="SUPER_ADMIN">
      {banner && (
        <div className={`mb-4 rounded-lg border px-4 py-2 text-sm ${
          banner.type === 'success' ? 'border-green-200 bg-green-50 text-green-800' : 'border-red-200 bg-red-50 text-red-800'
        }`}>
          {banner.text}
        </div>
      )}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">User management</h1>
          <p className="text-sm text-slate-500">Rapidly onboard field staff at national scale.</p>
        </div>
        <div className="flex gap-2">
          <button 
            onClick={() => setIsBulkImportModalOpen(true)}
            className="rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
          >
            Bulk Import
          </button>
          <button 
            onClick={handleCreate}
            className="rounded-lg bg-gold px-4 py-2 text-sm font-semibold text-white hover:bg-gold/90"
          >
            Invite user
          </button>
        </div>
      </div>
      <div className="mt-6 overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
        <table className="min-w-full divide-y divide-slate-100 text-sm">
          <thead className="bg-slate-50 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
            <tr>
              <th className="px-4 py-3">Name</th>
              <th className="px-4 py-3">Email</th>
              <th className="px-4 py-3">Role</th>
              <th className="px-4 py-3">Status</th>
              <th className="px-4 py-3 text-center">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100">
            {data?.data?.map((user: any) => (
              <tr key={user.id}>
                <td className="px-4 py-3 font-medium text-slate-900">{user.name}</td>
                <td className="px-4 py-3">{user.email}</td>
                <td className="px-4 py-3">{user.role}</td>
                <td className="px-4 py-3">
                  <span className={`rounded-full px-2 py-1 text-xs font-semibold ${user.active ? 'bg-brand/10 text-brand' : 'bg-slate-100 text-slate-500'}`}>
                    {user.active ? 'Active' : 'Inactive'}
                  </span>
                </td>
                <td className="px-4 py-3 text-center space-x-2">
                  <button
                    onClick={() => handleEdit(user)}
                    className="rounded-lg bg-slate-100 p-1.5 text-slate-600 hover:bg-slate-200 transition-colors"
                    title="Edit User"
                  >
                    <Edit className="h-4 w-4" />
                  </button>
                  <button
                    onClick={() => initiateReset.mutate(user.id)}
                    disabled={resettingId === user.id}
                    className="rounded-lg bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-700 hover:bg-slate-200 disabled:opacity-50"
                  >
                    {resettingId === user.id ? 'Sending...' : 'Reset Password'}
                  </button>
                  <button
                    onClick={() => toggleStatus.mutate({ userId: user.id, active: !user.active })}
                    disabled={mutatingUserId === user.id && toggleStatus.isPending}
                    className={`rounded-lg px-3 py-1 text-xs font-semibold transition ${
                      user.active
                        ? 'bg-red-50 text-red-700 hover:bg-red-100'
                        : 'bg-green-50 text-green-700 hover:bg-green-100'
                    } disabled:opacity-50`}
                  >
                    {mutatingUserId === user.id && toggleStatus.isPending
                      ? 'Saving...'
                      : user.active
                        ? 'Deactivate'
                        : 'Activate'}
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="mt-8 rounded-2xl border border-slate-100 bg-white p-4 shadow-sm">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-lg font-semibold text-slate-900">Pending password approvals</h2>
            <p className="text-sm text-slate-500">Approve or hold password change requests from field staff.</p>
          </div>
          {passwordRequestsLoading && <span className="text-xs text-slate-400">Loading…</span>}
        </div>

        {requests.length === 0 ? (
          <p className="mt-4 rounded-lg bg-slate-50 px-4 py-6 text-center text-sm text-slate-500">No pending requests.</p>
        ) : (
          <div className="mt-4 space-y-3">
            {requests.map((request: any) => (
              <div key={request.id} className="flex flex-col gap-3 rounded-xl border border-slate-200 p-4 md:flex-row md:items-center md:justify-between">
                <div>
                  <p className="text-sm font-semibold text-slate-900">{request.name}</p>
                  <p className="text-xs text-slate-500">{request.email}</p>
                  <p className="text-xs text-slate-500">Requested {new Date(request.created_at).toLocaleString()}</p>
                </div>
                <div className="flex w-full flex-col gap-2 md:w-auto md:flex-row md:items-center">
                  <input
                    type="text"
                    value={codeInputs[request.id] ?? ''}
                    onChange={(e) => setCodeInputs((prev) => ({ ...prev, [request.id]: e.target.value }))}
                    placeholder="Enter approval code"
                    className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-brand focus:outline-none md:w-56"
                  />
                  <button
                    onClick={() => approveRequest.mutate({ requestId: request.id, code: codeInputs[request.id] ?? '' })}
                    disabled={!codeInputs[request.id] || (approvingId === request.id && approveRequest.isPending)}
                    className="rounded-lg bg-brand px-4 py-2 text-sm font-semibold text-white transition hover:bg-brand/90 disabled:opacity-50"
                  >
                    {approvingId === request.id && approveRequest.isPending ? 'Approving…' : 'Approve'}
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
      <UserModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        user={editingUser}
        onSuccess={(msg) => setBanner({ type: 'success', text: msg })}
        onError={(msg) => setBanner({ type: 'error', text: msg })}
      />
      <BulkImportUsersModal 
        isOpen={isBulkImportModalOpen} 
        onClose={() => setIsBulkImportModalOpen(false)} 
        onSuccess={(text) => setBanner({ type: 'success', text })}
        onError={(text) => setBanner({ type: 'error', text })}
      />
    </LayoutShell>
  );
}
