import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useRoles, useCreateRole, useUpdateRole, useDeleteRole } from '@/api/hooks';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import { EmptyState } from '@/components/ui/EmptyState';
import { Skeleton } from '@/components/ui/Skeleton';
import { useToast } from '@/components/ui/Toast';
import { Modal } from '@/components/ui/Modal';
import { ConfirmDialog } from '@/components/ui/ConfirmDialog';

interface Role {
  id: string;
  name: string;
  permissions: Record<string, any>;
  field_permissions?: Record<string, any>;
}

const ALL_PERMISSIONS = [
  { key: 'companies:read', label: 'Firmen lesen' },
  { key: 'companies:write', label: 'Firmen bearbeiten' },
  { key: 'contacts:read', label: 'Kontakte lesen' },
  { key: 'contacts:write', label: 'Kontakte bearbeiten' },
  { key: 'users:read', label: 'Benutzer lesen' },
  { key: 'users:write', label: 'Benutzer bearbeiten' },
  { key: 'audit:read', label: 'Audit-Log lesen' },
  { key: 'settings:write', label: 'Einstellungen bearbeiten' },
];

function isPermissionGranted(permissions: Record<string, any>, permKey: string): boolean {
  if (!permissions) return false;
  if (typeof permissions === 'boolean') return permissions;
  if (Array.isArray(permissions)) return permissions.includes(permKey);
  if (typeof permissions === 'object') {
    if (permKey in permissions) {
      const val = permissions[permKey];
      return val === true || val === 'true' || val === 1;
    }
    if ('all' in permissions && permissions.all === true) return true;
  }
  return false;
}

function togglePermission(
  permissions: Record<string, any>,
  permKey: string
): Record<string, any> {
  const current = isPermissionGranted(permissions, permKey);
  return { ...permissions, [permKey]: !current };
}

function getGrantedPermissionKeys(permissions: Record<string, any>): string[] {
  if (!permissions) return [];
  if (Array.isArray(permissions)) return permissions as string[];
  if (typeof permissions === 'object') {
    return Object.keys(permissions).filter(
      (k) => k !== 'all' && permissions[k] === true
    );
  }
  return [];
}

export function SettingsRolesPage() {
  const { t } = useTranslation();
  const toast = useToast();
  const { data, isLoading, isError, error, refetch } = useRoles();
  const createRoleMutation = useCreateRole();
  const updateRoleMutation = useUpdateRole();
  const deleteRoleMutation = useDeleteRole();

  const [createOpen, setCreateOpen] = useState(false);
  const [newRoleName, setNewRoleName] = useState('');
  const [newRolePermissions, setNewRolePermissions] = useState<Record<string, any>>({});
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [confirmDelete, setConfirmDelete] = useState<Role | null>(null);

  const roles: Role[] = data?.items ?? [];

  const handleCreateRole = async () => {
    if (!newRoleName.trim()) {
      toast.error(t('validation.required'));
      return;
    }
    try {
      await createRoleMutation.mutateAsync({
        name: newRoleName.trim(),
        permissions: newRolePermissions,
        field_permissions: {},
      });
      toast.success(t('settings.roleCreated'));
      setNewRoleName('');
      setNewRolePermissions({});
      setCreateOpen(false);
    } catch (err: any) {
      toast.error(err.message || t('common.error'));
    }
  };

  const handleTogglePermission = (permKey: string, target: 'new' | 'edit') => {
    if (target === 'new') {
      setNewRolePermissions((prev) => togglePermission(prev, permKey));
    } else if (editingRole) {
      setEditingRole({
        ...editingRole,
        permissions: togglePermission(editingRole.permissions, permKey),
      });
    }
  };

  const handleSaveRole = async () => {
    if (!editingRole) return;
    try {
      await updateRoleMutation.mutateAsync({
        id: editingRole.id,
        data: {
          name: editingRole.name,
          permissions: editingRole.permissions,
          field_permissions: editingRole.field_permissions || {},
        },
      });
      toast.success(t('settings.roleUpdated'));
      setEditingRole(null);
    } catch (err: any) {
      toast.error(err.message || t('common.error'));
    }
  };

  const handleDeleteRole = async () => {
    if (!confirmDelete) return;
    try {
      await deleteRoleMutation.mutateAsync(confirmDelete.id);
      toast.success(t('settings.roleDeleted'));
      setConfirmDelete(null);
    } catch (err: any) {
      toast.error(err.message || t('common.error'));
    }
  };

  if (isLoading) {
    return (
      <div className="p-6 max-w-4xl mx-auto" data-testid="settings-roles-page">
        <Skeleton className="h-8 w-48 mb-6" />
        <div className="space-y-3">
          <Skeleton className="h-16" />
          <Skeleton className="h-16" />
          <Skeleton className="h-16" />
        </div>
      </div>
    );
  }

  if (isError) {
    return (
      <div className="p-6 max-w-4xl mx-auto" data-testid="settings-roles-page">
        <h1 className="text-2xl font-bold text-secondary-900 mb-6">{t('settings.roles')}</h1>
        <EmptyState
          title={t('common.error')}
          action={<Button onClick={() => refetch()}>{t('common.reset')}</Button>}
        >
          <p className="text-sm text-secondary-500">{error?.message || t('common.error')}</p>
        </EmptyState>
      </div>
    );
  }

  return (
    <div className="p-6 max-w-4xl mx-auto" data-testid="settings-roles-page">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-secondary-900">{t('settings.roles')}</h1>
        <Button onClick={() => setCreateOpen(true)} data-testid="create-role-btn">
          {t('settings.createRole')}
        </Button>
      </div>

      {roles.length === 0 ? (
        <EmptyState
          title={t('settings.noRoles')}
          action={<Button onClick={() => setCreateOpen(true)}>{t('settings.createRole')}</Button>}
        />
      ) : (
        <div className="space-y-4">
          {roles.map((role) => {
            const grantedKeys = getGrantedPermissionKeys(role.permissions);
            return (
              <Card key={role.id}>
                <div className="flex items-center justify-between mb-3">
                  <h3 className="text-lg font-semibold text-secondary-900">{role.name}</h3>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="secondary"
                      size="sm"
                      onClick={() => setEditingRole(role)}
                      data-testid={`edit-role-${role.id}`}
                    >
                      {t('common.edit')}
                    </Button>
                    <Button
                      variant="danger"
                      size="sm"
                      onClick={() => setConfirmDelete(role)}
                      data-testid={`delete-role-${role.id}`}
                    >
                      {t('common.delete')}
                    </Button>
                  </div>
                </div>
                <div className="flex flex-wrap gap-2">
                  {grantedKeys.length === 0 ? (
                    <span className="text-sm text-secondary-500">—</span>
                  ) : (
                    grantedKeys.map((perm) => {
                      const label = ALL_PERMISSIONS.find((p) => p.key === perm)?.label || perm;
                      return <Badge key={perm} variant="primary">{label}</Badge>;
                    })
                  )}
                </div>
              </Card>
            );
          })}
        </div>
      )}

      <Modal open={createOpen} onClose={() => setCreateOpen(false)} title={t('settings.createRole')}>
        <div className="space-y-4" data-testid="create-role-form">
          <Input
            label={t('settings.roleName')}
            value={newRoleName}
            onChange={(e) => setNewRoleName(e.target.value)}
            placeholder="z.B. Vertrieb"
            data-testid="new-role-name"
          />
          <div>
            <label className="block text-sm font-medium text-secondary-700 mb-2">{t('settings.permissions')}</label>
            <div className="space-y-2">
              {ALL_PERMISSIONS.map((perm) => (
                <label key={perm.key} className="flex items-center gap-2 p-2 rounded-md hover:bg-secondary-50 cursor-pointer min-h-touch">
                  <input
                    type="checkbox"
                    checked={isPermissionGranted(newRolePermissions, perm.key)}
                    onChange={() => handleTogglePermission(perm.key, 'new')}
                    className="w-4 h-4 rounded border-secondary-300 text-primary-600 focus:ring-primary-500"
                  />
                  <span className="text-sm text-secondary-900">{perm.label}</span>
                </label>
              ))}
            </div>
          </div>
          <div className="flex justify-end gap-3">
            <Button variant="secondary" onClick={() => setCreateOpen(false)}>{t('common.cancel')}</Button>
            <Button
              onClick={handleCreateRole}
              isLoading={createRoleMutation.isPending}
              data-testid="save-role-btn"
            >
              {t('common.save')}
            </Button>
          </div>
        </div>
      </Modal>

      <Modal open={!!editingRole} onClose={() => setEditingRole(null)} title={t('settings.roles') + ' — ' + (editingRole?.name || '')}>
        {editingRole && (
          <div className="space-y-4" data-testid="edit-role-form">
            <Input
              label={t('settings.roleName')}
              value={editingRole.name}
              onChange={(e) => setEditingRole({ ...editingRole, name: e.target.value })}
            />
            <div>
              <label className="block text-sm font-medium text-secondary-700 mb-2">{t('settings.permissions')}</label>
              <div className="space-y-2">
                {ALL_PERMISSIONS.map((perm) => (
                  <label key={perm.key} className="flex items-center gap-2 p-2 rounded-md hover:bg-secondary-50 cursor-pointer min-h-touch">
                    <input
                      type="checkbox"
                      checked={isPermissionGranted(editingRole.permissions, perm.key)}
                      onChange={() => handleTogglePermission(perm.key, 'edit')}
                      className="w-4 h-4 rounded border-secondary-300 text-primary-600 focus:ring-primary-500"
                    />
                    <span className="text-sm text-secondary-900">{perm.label}</span>
                  </label>
                ))}
              </div>
            </div>
            <div className="flex justify-end gap-3">
              <Button variant="secondary" onClick={() => setEditingRole(null)}>{t('common.cancel')}</Button>
              <Button
                onClick={handleSaveRole}
                isLoading={updateRoleMutation.isPending}
                data-testid="update-role-btn"
              >
                {t('common.save')}
              </Button>
            </div>
          </div>
        )}
      </Modal>

      <ConfirmDialog
        open={!!confirmDelete}
        title={t('common.delete')}
        message={`${t('common.delete')}: ${confirmDelete?.name}?`}
        variant="danger"
        onConfirm={handleDeleteRole}
        onCancel={() => setConfirmDelete(null)}
      />
    </div>
  );
}
