import { useState } from 'react';
import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query';
import api from '../api/client';
import { Modal } from '../components/Modal';
import { UserFormModal } from './UserFormModal';

interface User {
  id: string;
  email: string;
  firstName: string;
  lastName: string;
  role: string;
  isActive: boolean;
  lastLogin: string | null;
  createdAt: string;
}

interface UsersResponse {
  data: User[];
  meta: {
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  };
}

const ROLE_LABELS: Record<string, string> = {
  USER: 'Benutzer',
  TENANT_ADMIN: 'Mandanten-Admin',
  PLATFORM_ADMIN: 'Plattform-Admin',
};

const ROLE_COLORS: Record<string, { bg: string; color: string }> = {
  PLATFORM_ADMIN: { bg: '#dbeafe', color: '#1e40af' },
  TENANT_ADMIN: { bg: '#fef3c7', color: '#92400e' },
  USER: { bg: '#f3f4f6', color: '#374151' },
};

const thStyle: React.CSSProperties = {
  padding: '0.75rem 1rem',
  textAlign: 'left',
  fontSize: '0.75rem',
  textTransform: 'uppercase',
  color: 'var(--color-text-muted)',
};

export function AdminUsersPage() {
  const queryClient = useQueryClient();
  const [isCreateModalOpen, setCreateModalOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [deletingUser, setDeletingUser] = useState<User | null>(null);

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

  const toggleActiveMutation = useMutation({
    mutationFn: ({ id, isActive }: { id: string; isActive: boolean }) =>
      api.patch(`/users/${id}`, { isActive }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'users'] });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => api.delete(`/users/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'users'] });
      setDeletingUser(null);
    },
  });

  if (isLoading) return <p>Laden...</p>;
  if (error) return <p style={{ color: 'var(--color-error)' }}>Fehler beim Laden der Benutzer</p>;

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
        <h1 style={{ fontSize: '1.5rem', fontWeight: 600 }}>Benutzerverwaltung</h1>
        <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
          <span style={{ color: 'var(--color-text-muted)', fontSize: '0.875rem' }}>
            {data?.meta.total ?? 0} Benutzer gesamt
          </span>
          <button
            onClick={() => setCreateModalOpen(true)}
            style={{
              padding: '0.5rem 1rem',
              background: 'var(--color-primary)',
              color: 'white',
              border: 'none',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.875rem',
              fontWeight: 600,
              cursor: 'pointer',
            }}
          >
            + Neuer Benutzer
          </button>
        </div>
      </div>

      <div style={{
        background: 'var(--color-bg-card)',
        borderRadius: 'var(--radius-md)',
        boxShadow: 'var(--shadow-sm)',
        border: '1px solid var(--color-border)',
        overflow: 'hidden',
      }}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ borderBottom: '1px solid var(--color-border)', background: 'var(--color-bg)' }}>
              <th style={thStyle}>Name</th>
              <th style={thStyle}>E-Mail</th>
              <th style={thStyle}>Rolle</th>
              <th style={thStyle}>Status</th>
              <th style={thStyle}>Letzter Login</th>
              <th style={thStyle}>Aktionen</th>
            </tr>
          </thead>
          <tbody>
            {data?.data.map((user) => {
              const roleStyle = ROLE_COLORS[user.role] ?? ROLE_COLORS.USER;
              return (
                <tr key={user.id} style={{ borderBottom: '1px solid var(--color-border)' }}>
                  <td style={{ padding: '0.75rem 1rem', fontSize: '0.875rem' }}>
                    {user.firstName} {user.lastName}
                  </td>
                  <td style={{ padding: '0.75rem 1rem', fontSize: '0.875rem', color: 'var(--color-text-secondary)' }}>
                    {user.email}
                  </td>
                  <td style={{ padding: '0.75rem 1rem' }}>
                    <span style={{
                      display: 'inline-block',
                      padding: '0.125rem 0.5rem',
                      borderRadius: '9999px',
                      fontSize: '0.75rem',
                      fontWeight: 500,
                      background: roleStyle.bg,
                      color: roleStyle.color,
                    }}>
                      {ROLE_LABELS[user.role] ?? user.role}
                    </span>
                  </td>
                  <td style={{ padding: '0.75rem 1rem' }}>
                    <span style={{
                      display: 'inline-block',
                      width: 8,
                      height: 8,
                      borderRadius: '50%',
                      background: user.isActive ? 'var(--color-success)' : 'var(--color-error)',
                      marginRight: '0.375rem',
                    }} />
                    <span style={{ fontSize: '0.875rem' }}>{user.isActive ? 'Aktiv' : 'Inaktiv'}</span>
                  </td>
                  <td style={{ padding: '0.75rem 1rem', fontSize: '0.875rem', color: 'var(--color-text-muted)' }}>
                    {user.lastLogin ? new Date(user.lastLogin).toLocaleDateString('de-DE') : 'Nie'}
                  </td>
                  <td style={{ padding: '0.75rem 1rem' }}>
                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                      <button
                        onClick={() => setEditingUser(user)}
                        style={{
                          padding: '0.25rem 0.625rem',
                          fontSize: '0.8125rem',
                          background: 'transparent',
                          border: '1px solid var(--color-border)',
                          borderRadius: 'var(--radius-sm)',
                          cursor: 'pointer',
                          color: 'var(--color-text-secondary)',
                        }}
                      >
                        Bearbeiten
                      </button>
                      <button
                        onClick={() => toggleActiveMutation.mutate({ id: user.id, isActive: !user.isActive })}
                        disabled={toggleActiveMutation.isPending}
                        style={{
                          padding: '0.25rem 0.625rem',
                          fontSize: '0.8125rem',
                          background: 'transparent',
                          border: `1px solid ${user.isActive ? '#fecaca' : '#bbf7d0'}`,
                          borderRadius: 'var(--radius-sm)',
                          cursor: 'pointer',
                          color: user.isActive ? 'var(--color-error)' : 'var(--color-success)',
                        }}
                      >
                        {user.isActive ? 'Deaktivieren' : 'Aktivieren'}
                      </button>
                      <button
                        onClick={() => setDeletingUser(user)}
                        style={{
                          padding: '0.25rem 0.625rem',
                          fontSize: '0.8125rem',
                          background: 'transparent',
                          border: '1px solid #fecaca',
                          borderRadius: 'var(--radius-sm)',
                          cursor: 'pointer',
                          color: 'var(--color-error)',
                        }}
                      >
                        Löschen
                      </button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Modal: Neuen Benutzer anlegen */}
      <UserFormModal
        isOpen={isCreateModalOpen}
        onClose={() => setCreateModalOpen(false)}
        onSuccess={() => setCreateModalOpen(false)}
      />

      {/* Modal: Benutzer bearbeiten */}
      <UserFormModal
        isOpen={!!editingUser}
        onClose={() => setEditingUser(null)}
        user={editingUser}
        onSuccess={() => setEditingUser(null)}
      />

      {/* Modal: Benutzer löschen — Bestätigung */}
      <Modal
        isOpen={!!deletingUser}
        onClose={() => setDeletingUser(null)}
        title="Benutzer löschen"
        maxWidth="420px"
      >
        <p style={{ fontSize: '0.9375rem', color: 'var(--color-text)', marginBottom: '0.5rem' }}>
          Soll der Benutzer <strong>{deletingUser?.firstName} {deletingUser?.lastName}</strong> ({deletingUser?.email}) wirklich gelöscht werden?
        </p>
        <p style={{ fontSize: '0.8125rem', color: 'var(--color-error)', marginBottom: '1.5rem' }}>
          Diese Aktion kann nicht rückgängig gemacht werden. Alle Daten des Benutzers werden unwiderruflich gelöscht.
        </p>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.75rem' }}>
          <button
            onClick={() => setDeletingUser(null)}
            disabled={deleteMutation.isPending}
            style={{
              padding: '0.5rem 1rem',
              background: 'transparent',
              border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.875rem',
              cursor: 'pointer',
              color: 'var(--color-text-secondary)',
            }}
          >
            Abbrechen
          </button>
          <button
            onClick={() => deletingUser && deleteMutation.mutate(deletingUser.id)}
            disabled={deleteMutation.isPending}
            style={{
              padding: '0.5rem 1rem',
              background: 'var(--color-error)',
              color: 'white',
              border: 'none',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.875rem',
              fontWeight: 600,
              cursor: deleteMutation.isPending ? 'wait' : 'pointer',
              opacity: deleteMutation.isPending ? 0.7 : 1,
            }}
          >
            {deleteMutation.isPending ? 'Löschen...' : 'Endgültig löschen'}
          </button>
        </div>
      </Modal>
    </div>
  );
}
