import React, { useState } from 'react';
import { AppLayout } from '../../components/layout/AppLayout';
import {
  Shield,
  Check,
  X,
  Minus,
  Crown,
  UserCog,
  User,
  Users,
  Eye,
  Lock,
  Unlock,
  Key,
} from 'lucide-react';

interface Permission {
  name: string;
  description: string;
}

interface RoleDef {
  id: string;
  label: string;
  icon: React.ReactNode;
  color: string;
  bgColor: string;
  description: string;
  permissions: Record<string, boolean>;
}

const PLATFORM_PERMISSIONS: Permission[] = [
  { name: 'Manage All Organizations', description: 'Create, edit, delete any organization' },
  { name: 'Manage All Users', description: 'Add, remove, modify any user account' },
  { name: 'View All Analytics', description: 'Access analytics across all organizations' },
  { name: 'Manage Integrations', description: 'Configure platform-wide integrations' },
  { name: 'View Audit Logs', description: 'Access full audit trail' },
  { name: 'Manage Portfolios', description: 'Create and manage portfolio groups' },
  { name: 'Manage Partners', description: 'Add and configure partner workspaces' },
  { name: 'Manage Email Campaigns', description: 'Create and manage email campaigns' },
  { name: 'Manage Leads', description: 'View and manage all leads platform-wide' },
  { name: 'System Settings', description: 'Modify platform-wide settings' },
];

const COMPANY_PERMISSIONS: Permission[] = [
  { name: 'Edit Company Profile', description: 'Modify company name, details, settings' },
  { name: 'Manage Company Users', description: 'Add/remove users within this company' },
  { name: 'View Company Analytics', description: 'Access company-specific analytics' },
  { name: 'Manage CRM Records', description: 'Create/edit/delete contacts, deals, leads' },
  { name: 'Manage Goals & Forecasts', description: 'Set and modify goals and forecasting data' },
  { name: 'View Company Audit Log', description: 'Access this company audit trail' },
];

const PLATFORM_ROLES: RoleDef[] = [
  {
    id: 'super_admin',
    label: 'Super Admin',
    icon: <Crown className="h-4 w-4" />,
    color: 'text-red-700',
    bgColor: 'bg-red-100',
    description: 'Full platform access across all organizations',
    permissions: {
      'Manage All Organizations': true,
      'Manage All Users': true,
      'View All Analytics': true,
      'Manage Integrations': true,
      'View Audit Logs': true,
      'Manage Portfolios': true,
      'Manage Partners': true,
      'Manage Email Campaigns': true,
      'Manage Leads': true,
      'System Settings': true,
    },
  },
  {
    id: 'admin',
    label: 'Admin',
    icon: <UserCog className="h-4 w-4" />,
    color: 'text-orange-700',
    bgColor: 'bg-orange-100',
    description: 'Full access within their organization',
    permissions: {
      'Manage All Organizations': false,
      'Manage All Users': false,
      'View All Analytics': false,
      'Manage Integrations': false,
      'View Audit Logs': true,
      'Manage Portfolios': false,
      'Manage Partners': false,
      'Manage Email Campaigns': true,
      'Manage Leads': true,
      'System Settings': false,
    },
  },
  {
    id: 'partner',
    label: 'Partner',
    icon: <Users className="h-4 w-4" />,
    color: 'text-blue-700',
    bgColor: 'bg-blue-100',
    description: 'Isolated partner workspace access',
    permissions: {
      'Manage All Organizations': false,
      'Manage All Users': false,
      'View All Analytics': false,
      'Manage Integrations': false,
      'View Audit Logs': false,
      'Manage Portfolios': false,
      'Manage Partners': false,
      'Manage Email Campaigns': false,
      'Manage Leads': false,
      'System Settings': false,
    },
  },
  {
    id: 'user',
    label: 'User',
    icon: <User className="h-4 w-4" />,
    color: 'text-gray-600',
    bgColor: 'bg-gray-100',
    description: 'Basic access within their organization',
    permissions: {
      'Manage All Organizations': false,
      'Manage All Users': false,
      'View All Analytics': false,
      'Manage Integrations': false,
      'View Audit Logs': false,
      'Manage Portfolios': false,
      'Manage Partners': false,
      'Manage Email Campaigns': false,
      'Manage Leads': false,
      'System Settings': false,
    },
  },
];

const COMPANY_ROLES_DATA: RoleDef[] = [
  {
    id: 'owner',
    label: 'Owner',
    icon: <Crown className="h-4 w-4" />,
    color: 'text-purple-700',
    bgColor: 'bg-purple-100',
    description: 'Full ownership with all company permissions',
    permissions: {
      'Edit Company Profile': true,
      'Manage Company Users': true,
      'View Company Analytics': true,
      'Manage CRM Records': true,
      'Manage Goals & Forecasts': true,
      'View Company Audit Log': true,
    },
  },
  {
    id: 'admin',
    label: 'Admin',
    icon: <UserCog className="h-4 w-4" />,
    color: 'text-indigo-700',
    bgColor: 'bg-indigo-100',
    description: 'Full admin within company except ownership',
    permissions: {
      'Edit Company Profile': true,
      'Manage Company Users': true,
      'View Company Analytics': true,
      'Manage CRM Records': true,
      'Manage Goals & Forecasts': true,
      'View Company Audit Log': true,
    },
  },
  {
    id: 'manager',
    label: 'Manager',
    icon: <User className="h-4 w-4" />,
    color: 'text-emerald-700',
    bgColor: 'bg-emerald-100',
    description: 'Can manage CRM and goals but not users',
    permissions: {
      'Edit Company Profile': false,
      'Manage Company Users': false,
      'View Company Analytics': true,
      'Manage CRM Records': true,
      'Manage Goals & Forecasts': true,
      'View Company Audit Log': false,
    },
  },
  {
    id: 'rep',
    label: 'Rep',
    icon: <Eye className="h-4 w-4" />,
    color: 'text-amber-700',
    bgColor: 'bg-amber-100',
    description: 'Can manage CRM records only',
    permissions: {
      'Edit Company Profile': false,
      'Manage Company Users': false,
      'View Company Analytics': false,
      'Manage CRM Records': true,
      'Manage Goals & Forecasts': false,
      'View Company Audit Log': false,
    },
  },
  {
    id: 'viewer',
    label: 'Viewer',
    icon: <Eye className="h-4 w-4" />,
    color: 'text-slate-600',
    bgColor: 'bg-slate-100',
    description: 'Read-only access to company data',
    permissions: {
      'Edit Company Profile': false,
      'Manage Company Users': false,
      'View Company Analytics': false,
      'Manage CRM Records': false,
      'Manage Goals & Forecasts': false,
      'View Company Audit Log': false,
    },
  },
];

function PermissionCell({ has }: { has: boolean }) {
  if (has) {
    return (
      <div className="flex justify-center">
        <div className="flex h-6 w-6 items-center justify-center rounded bg-green-100">
          <Check className="h-3.5 w-3.5 text-green-600" />
        </div>
      </div>
    );
  }
  return (
    <div className="flex justify-center">
      <div className="flex h-6 w-6 items-center justify-center rounded bg-surface-100">
        <Minus className="h-3.5 w-3.5 text-surface-400" />
      </div>
    </div>
  );
}

function RolePermissionsTable({
  roles,
  permissions,
  title,
}: {
  roles: RoleDef[];
  permissions: Permission[];
  title: string;
}) {
  return (
    <div className="rounded-xl border border-surface-200 bg-white overflow-hidden">
      <div className="border-b border-surface-200 px-5 py-4">
        <h3 className="text-sm font-semibold text-surface-900">{title}</h3>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full text-xs">
          <thead>
            <tr className="border-b border-surface-200">
              <th className="pb-3 pl-5 text-left font-medium text-surface-500 min-w-[160px]">Role</th>
              {permissions.map((perm) => (
                <th key={perm.name} className="pb-3 px-2 text-center font-medium text-surface-500 whitespace-nowrap min-w-[80px]">
                  {perm.name}
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-surface-100">
            {roles.map((role) => (
              <tr key={role.id} className="hover:bg-surface-50">
                <td className="py-3 pl-5">
                  <div className="flex items-center gap-2">
                    <div className={`flex h-7 w-7 items-center justify-center rounded-lg ${role.bgColor} ${role.color}`}>
                      {role.icon}
                    </div>
                    <div>
                      <p className="text-sm font-medium text-surface-900">{role.label}</p>
                      <p className="text-xs text-surface-500">{role.description}</p>
                    </div>
                  </div>
                </td>
                {permissions.map((perm) => (
                  <td key={perm.name} className="py-3 px-2">
                    <PermissionCell has={role.permissions[perm.name] ?? false} />
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

export function AccessLevelsPage() {
  const [activeTab, setActiveTab] = useState<'platform' | 'company'>('platform');

  return (
    <AppLayout title="Access Levels">
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-xl sm:text-2xl font-bold text-surface-900">Access Levels</h1>
        <p className="mt-1 text-sm text-surface-500">
          Role-based access control configuration for platform and company permissions
        </p>
        <div className="mt-2 flex items-center gap-2">
          <div className="flex h-5 w-5 items-center justify-center rounded bg-brand-100">
            <Key className="h-3 w-3 text-brand-600" />
          </div>
          <span className="text-xs text-surface-500">
            Roles define what users can see and do. Users inherit permissions from both their Platform Role and Company Role.
          </span>
        </div>
      </div>

      {/* Tab Navigation */}
      <div className="mb-6 flex gap-2">
        <button
          onClick={() => setActiveTab('platform')}
          className={`inline-flex items-center gap-2 rounded-lg px-4 py-2.5 text-sm font-medium min-h-[44px] transition-colors ${
            activeTab === 'platform'
              ? 'bg-brand-600 text-white'
              : 'bg-white border border-surface-300 text-surface-700 hover:bg-surface-50'
          }`}
        >
          <Shield className="h-4 w-4" />
          Platform Roles
        </button>
        <button
          onClick={() => setActiveTab('company')}
          className={`inline-flex items-center gap-2 rounded-lg px-4 py-2.5 text-sm font-medium min-h-[44px] transition-colors ${
            activeTab === 'company'
              ? 'bg-brand-600 text-white'
              : 'bg-white border border-surface-300 text-surface-700 hover:bg-surface-50'
          }`}
        >
          <UserCog className="h-4 w-4" />
          Company Roles
        </button>
      </div>

      {/* Info Banner */}
      <div className="mb-6 flex items-start gap-3 rounded-lg border border-blue-200 bg-blue-50 px-4 py-3">
        <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-blue-100">
          <Lock className="h-4 w-4 text-blue-600" />
        </div>
        <div>
          <p className="text-sm font-medium text-blue-800">
            {activeTab === 'platform'
              ? 'Platform roles control cross-organization access'
              : 'Company roles control within-organization permissions'}
          </p>
          <p className="text-xs text-blue-600 mt-0.5">
            {activeTab === 'platform'
              ? 'Super Admins have unrestricted access. Admins are scoped to their organization. Partners have isolated workspaces.'
              : 'Owner has full control. Admin mirrors Owner without ownership rights. Manager handles CRM and goals. Rep manages records only. Viewer is read-only.'}
          </p>
        </div>
      </div>

      {/* Permission Matrix */}
      <div className="space-y-6">
        {activeTab === 'platform' ? (
          <RolePermissionsTable
            roles={PLATFORM_ROLES}
            permissions={PLATFORM_PERMISSIONS}
            title="Platform Role Permissions Matrix"
          />
        ) : (
          <RolePermissionsTable
            roles={COMPANY_ROLES_DATA}
            permissions={COMPANY_PERMISSIONS}
            title="Company Role Permissions Matrix"
          />
        )}
      </div>

      {/* Role Summary Cards */}
      <div className="mt-6">
        <h3 className="mb-3 text-sm font-semibold text-surface-900">
          {activeTab === 'platform' ? 'Platform Role Summary' : 'Company Role Summary'}
        </h3>
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {(activeTab === 'platform' ? PLATFORM_ROLES : COMPANY_ROLES_DATA).map((role) => {
            const allowed = Object.values(role.permissions).filter(Boolean).length;
            const total = Object.keys(role.permissions).length;
            const pct = Math.round((allowed / total) * 100);

            return (
              <div key={role.id} className="rounded-xl border border-surface-200 bg-white p-4">
                <div className="flex items-center gap-3 mb-3">
                  <div className={`flex h-10 w-10 items-center justify-center rounded-lg ${role.bgColor} ${role.color}`}>
                    {role.icon}
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="text-sm font-semibold text-surface-900">{role.label}</p>
                    <p className="text-xs text-surface-500 truncate">{role.description}</p>
                  </div>
                </div>
                <div className="mt-3">
                  <div className="flex items-center justify-between text-xs text-surface-500 mb-1">
                    <span>Permissions</span>
                    <span className="font-medium">{allowed}/{total} ({pct}%)</span>
                  </div>
                  <div className="h-2 w-full overflow-hidden rounded-full bg-surface-100">
                    <div
                      className={`h-full rounded-full ${role.bgColor.replace('/10', '').replace('bg-', 'bg-')}`}
                      style={{ width: `${pct}%` }}
                    />
                  </div>
                </div>
                {allowed === 0 && (
                  <div className="mt-2 flex items-center gap-1">
                    <Lock className="h-3 w-3 text-surface-400" />
                    <span className="text-xs text-surface-400">View-only access</span>
                  </div>
                )}
                {allowed === total && (
                  <div className="mt-2 flex items-center gap-1">
                    <Unlock className="h-3 w-3 text-green-500" />
                    <span className="text-xs text-green-600">Full access</span>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </AppLayout>
  );
}
