import { useState, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { rbacApi, AccessPolicy, AdminRole } from '@/api/rbac';
import { PermissionGate } from '@/components/auth/PermissionGate';
import { usePlatform } from '@/platform/hooks/usePlatform';
import { useFocusTrap } from '@/hooks/useFocusTrap';
import { StatCard } from '@/components/stats';
import {
  BackIcon,
  BoltIcon,
  CalendarIcon,
  CheckCircleIcon,
  ClockIcon,
  EditIcon,
  GlobeIcon,
  PlusIcon,
  ShieldIcon,
  TrashIcon,
  XCircleIcon,
} from '@/components/icons';

interface PolicyConditions {
  time_range?: { start: string; end: string };
  ip_whitelist?: string[];
  rate_limit?: number;
  weekdays?: number[];
}

function parseConditions(raw: Record<string, unknown>): PolicyConditions {
  const result: PolicyConditions = {};

  if (raw.time_range && typeof raw.time_range === 'object') {
    const tr = raw.time_range as Record<string, unknown>;
    if (typeof tr.start === 'string' && typeof tr.end === 'string') {
      result.time_range = { start: tr.start, end: tr.end };
    }
  }

  if (Array.isArray(raw.ip_whitelist)) {
    result.ip_whitelist = raw.ip_whitelist.filter((ip): ip is string => typeof ip === 'string');
  }

  if (typeof raw.rate_limit === 'number') {
    result.rate_limit = raw.rate_limit;
  }

  if (Array.isArray(raw.weekdays)) {
    result.weekdays = raw.weekdays.filter((d): d is number => typeof d === 'number');
  }

  return result;
}

interface EffectBadgeProps {
  effect: 'allow' | 'deny';
  className?: string;
}

function EffectBadge({ effect, className }: EffectBadgeProps) {
  const { t } = useTranslation();

  const isAllow = effect === 'allow';
  return (
    <span
      className={`inline-flex items-center rounded-md border px-2 py-0.5 text-xs font-semibold ${
        isAllow
          ? 'border-success-500/30 bg-success-500/10 text-success-400'
          : 'border-error-500/30 bg-error-500/10 text-error-400'
      } ${className ?? ''}`}
    >
      {isAllow ? t('admin.policies.effectAllow') : t('admin.policies.effectDeny')}
    </span>
  );
}

export default function AdminPolicies() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { capabilities } = usePlatform();

  const [deleteConfirm, setDeleteConfirm] = useState<number | null>(null);
  const deleteDialogRef = useFocusTrap<HTMLDivElement>(deleteConfirm !== null, {
    onEscape: () => setDeleteConfirm(null),
  });
  const [formError, setFormError] = useState<string | null>(null);

  // Queries
  const {
    data: policies,
    isLoading: policiesLoading,
    error: policiesError,
  } = useQuery({
    queryKey: ['admin-policies'],
    queryFn: rbacApi.getPolicies,
  });

  const { data: roles } = useQuery({
    queryKey: ['admin-roles'],
    queryFn: rbacApi.getRoles,
  });

  // Mutations
  const deleteMutation = useMutation({
    mutationFn: rbacApi.deletePolicy,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-policies'] });
      setDeleteConfirm(null);
    },
    onError: () => {
      setDeleteConfirm(null);
      setFormError(t('admin.policies.errors.deleteFailed'));
    },
  });

  // Derived data
  const rolesMap = useMemo(() => {
    const map = new Map<number, AdminRole>();
    if (roles) {
      for (const role of roles) {
        map.set(role.id, role);
      }
    }
    return map;
  }, [roles]);

  const sortedPolicies = useMemo(() => {
    if (!policies) return [];
    return [...policies].sort((a, b) => b.priority - a.priority);
  }, [policies]);

  // Condition icons renderer
  const renderConditionIcons = useCallback(
    (conditions: Record<string, unknown>) => {
      const parsed = parseConditions(conditions);
      const icons: React.ReactNode[] = [];

      if (parsed.time_range) {
        icons.push(
          <span
            key="time"
            className="inline-flex items-center gap-1 rounded bg-dark-700 px-1.5 py-0.5 text-xs text-dark-300"
            title={t('admin.policies.conditions.timeRange')}
          >
            <ClockIcon className="h-4 w-4" />
            {parsed.time_range.start}-{parsed.time_range.end}
          </span>,
        );
      }

      if (parsed.ip_whitelist && parsed.ip_whitelist.length > 0) {
        icons.push(
          <span
            key="ip"
            className="inline-flex items-center gap-1 rounded bg-dark-700 px-1.5 py-0.5 text-xs text-dark-300"
            title={t('admin.policies.conditions.ipWhitelist')}
          >
            <GlobeIcon className="h-4 w-4" />
            {t('admin.policies.conditions.ipCount', { count: parsed.ip_whitelist.length })}
          </span>,
        );
      }

      if (parsed.rate_limit !== undefined) {
        icons.push(
          <span
            key="rate"
            className="inline-flex items-center gap-1 rounded bg-dark-700 px-1.5 py-0.5 text-xs text-dark-300"
            title={t('admin.policies.conditions.rateLimit')}
          >
            <BoltIcon className="h-4 w-4" />
            {t('admin.policies.conditions.rateValue', { count: parsed.rate_limit })}
          </span>,
        );
      }

      if (parsed.weekdays && parsed.weekdays.length > 0 && parsed.weekdays.length < 7) {
        const dayOrder = [1, 2, 3, 4, 5, 6, 0];
        const sorted = dayOrder.filter((d) => parsed.weekdays!.includes(d));
        const dayNames = sorted.map((d) => t(`admin.policies.conditions.day${d}`));
        icons.push(
          <span
            key="weekdays"
            className="inline-flex items-center gap-1 rounded bg-dark-700 px-1.5 py-0.5 text-xs text-dark-300"
            title={t('admin.policies.conditions.weekdays')}
          >
            <CalendarIcon className="h-4 w-4" />
            {dayNames.join(', ')}
          </span>,
        );
      }

      return icons;
    },
    [t],
  );

  const getRoleName = useCallback(
    (policy: AccessPolicy): string => {
      if (policy.role_name) return policy.role_name;
      if (policy.role_id === null) return t('admin.policies.global');
      const role = rolesMap.get(policy.role_id);
      return role?.name ?? t('admin.policies.unknownRole');
    },
    [rolesMap, t],
  );

  return (
    <div className="animate-fade-in">
      {/* Header */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-3">
          {!capabilities.hasBackButton && (
            <button
              onClick={() => navigate('/admin')}
              className="flex h-10 w-10 items-center justify-center rounded-xl border border-dark-700 bg-dark-800 transition-colors hover:border-dark-600"
            >
              <BackIcon />
            </button>
          )}
          <div>
            <h1 className="text-xl font-semibold text-dark-100">{t('admin.policies.title')}</h1>
            <p className="text-sm text-dark-400">{t('admin.policies.subtitle')}</p>
          </div>
        </div>
        <PermissionGate permission="roles:create">
          <button
            onClick={() => navigate('/admin/policies/create')}
            className="flex items-center justify-center gap-2 rounded-lg bg-accent-500 px-4 py-2 text-on-accent transition-colors hover:bg-accent-600"
          >
            <PlusIcon />
            {t('admin.policies.createPolicy')}
          </button>
        </PermissionGate>
      </div>

      {/* Error message */}
      {formError && (
        <div className="mb-4 rounded-lg border border-error-500/30 bg-error-500/10 p-3">
          <p className="text-sm text-error-400">{formError}</p>
        </div>
      )}

      {/* Stats Overview */}
      {sortedPolicies.length > 0 && (
        <div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
          <StatCard
            label={t('admin.policies.stats.total')}
            value={sortedPolicies.length}
            icon={<ShieldIcon className="h-5 w-5" />}
            tone="neutral"
          />
          <StatCard
            label={t('admin.policies.stats.allow')}
            value={sortedPolicies.filter((p) => p.effect === 'allow').length}
            icon={<CheckCircleIcon className="h-5 w-5" />}
            tone="success"
          />
          <StatCard
            label={t('admin.policies.stats.deny')}
            value={sortedPolicies.filter((p) => p.effect === 'deny').length}
            icon={<XCircleIcon className="h-5 w-5" />}
            tone="error"
          />
          <StatCard
            label={t('admin.policies.stats.active')}
            value={sortedPolicies.filter((p) => p.is_active).length}
            icon={<BoltIcon className="h-5 w-5" />}
            tone="accent"
          />
        </div>
      )}

      {/* Policies List */}
      {policiesLoading ? (
        <div className="flex items-center justify-center py-12">
          <div className="h-8 w-8 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
        </div>
      ) : policiesError ? (
        <div className="py-12 text-center">
          <p className="text-error-400">{t('admin.policies.errors.loadFailed')}</p>
        </div>
      ) : sortedPolicies.length === 0 ? (
        <div className="py-12 text-center">
          <ShieldIcon />
          <p className="mt-2 text-dark-400">{t('admin.policies.noPolicies')}</p>
        </div>
      ) : (
        <div className="space-y-3">
          {sortedPolicies.map((policy) => {
            const conditionIcons = renderConditionIcons(policy.conditions);
            const roleName = getRoleName(policy);

            return (
              <div
                key={policy.id}
                className={`rounded-xl border bg-dark-800 p-4 transition-colors ${
                  policy.is_active ? 'border-dark-700' : 'border-dark-700/50 opacity-60'
                }`}
              >
                <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
                  <div className="min-w-0 flex-1">
                    {/* Policy name + effect badge */}
                    <div className="mb-2 flex flex-wrap items-center gap-2">
                      <span className="font-medium text-dark-100">{policy.name}</span>
                      <EffectBadge effect={policy.effect} />
                      {!policy.is_active && (
                        <span className="rounded bg-dark-600 px-1.5 py-0.5 text-xs text-dark-400">
                          {t('admin.policies.inactiveBadge')}
                        </span>
                      )}
                    </div>

                    {/* Resource + actions */}
                    <div className="mb-2 flex flex-wrap items-center gap-2 text-sm">
                      <span className="rounded bg-dark-700 px-2 py-0.5 text-xs text-accent-400">
                        {t(
                          `admin.roles.form.permissionSections.${policy.resource}`,
                          policy.resource,
                        )}
                      </span>
                      <span className="text-dark-500">:</span>
                      <span className="text-xs text-dark-300">
                        {(policy.actions ?? [])
                          .map((a) => t(`admin.roles.form.permissionActions.${a}`, a))
                          .join(', ')}
                      </span>
                    </div>

                    {/* Info row */}
                    <div className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-dark-400">
                      <span>
                        {t('admin.policies.roleLabel')}: {roleName}
                      </span>
                      <span>
                        {t('admin.policies.priorityLabel')}: {policy.priority}
                      </span>
                    </div>

                    {/* Condition icons */}
                    {conditionIcons.length > 0 && (
                      <div className="mt-2 flex flex-wrap gap-1.5">{conditionIcons}</div>
                    )}
                  </div>

                  {/* Actions */}
                  <div className="flex items-center gap-2 border-t border-dark-700 pt-3 sm:border-0 sm:pt-0">
                    <PermissionGate permission="roles:edit">
                      <button
                        onClick={() => navigate(`/admin/policies/${policy.id}/edit`)}
                        className="flex-1 rounded-lg bg-dark-700 p-2 text-dark-300 transition-colors hover:bg-dark-600 hover:text-dark-100 sm:flex-none"
                        title={t('admin.policies.actions.edit')}
                      >
                        <EditIcon />
                      </button>
                    </PermissionGate>
                    <PermissionGate permission="roles:delete">
                      <button
                        onClick={() => setDeleteConfirm(policy.id)}
                        className="flex-1 rounded-lg bg-dark-700 p-2 text-dark-300 transition-colors hover:bg-error-500/20 hover:text-error-400 sm:flex-none"
                        title={t('admin.policies.actions.delete')}
                      >
                        <TrashIcon className="h-4 w-4" />
                      </button>
                    </PermissionGate>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Delete Confirmation */}
      {deleteConfirm !== null && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div
            className="fixed inset-0 bg-dark-950/60"
            onClick={() => setDeleteConfirm(null)}
            aria-hidden="true"
          />
          <div
            ref={deleteDialogRef}
            role="dialog"
            aria-modal="true"
            aria-labelledby="policy-delete-title"
            tabIndex={-1}
            className="relative w-full max-w-sm rounded-xl border border-dark-700 bg-dark-800 p-6"
          >
            <h3 id="policy-delete-title" className="mb-2 text-lg font-semibold text-dark-100">
              {t('admin.policies.confirm.title')}
            </h3>
            <p className="mb-6 text-dark-400">{t('admin.policies.confirm.text')}</p>
            <div className="flex justify-end gap-3">
              <button
                onClick={() => setDeleteConfirm(null)}
                className="px-4 py-2 text-dark-300 transition-colors hover:text-dark-100"
              >
                {t('admin.policies.confirm.cancel')}
              </button>
              <button
                onClick={() => deleteMutation.mutate(deleteConfirm)}
                disabled={deleteMutation.isPending}
                className="rounded-lg bg-error-500 px-4 py-2 text-white transition-colors hover:bg-error-600 disabled:opacity-50"
              >
                {deleteMutation.isPending
                  ? t('admin.policies.confirm.deleting')
                  : t('admin.policies.confirm.delete')}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
