import React, { useState, useCallback, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { adminApi } from '../../api/admin';
import { AppLayout } from '../../components/layout/AppLayout';
import { PageLoader } from '../../components/ui/LoadingSpinner';
import { Search, User as UserIcon, ChevronDown, Check, Loader2, Plus, Trash2, X, AlertTriangle, Building2 } from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
import type { ApiUser, PlatformRole, CompanyRole, PaginatedResponse, Organization } from '../../types';

const PLATFORM_ROLES: { value: PlatformRole; label: string; color: string }[] = [
  { value: 'super_admin', label: 'Super Admin', color: 'bg-red-100 text-red-700' },
  { value: 'admin', label: 'Admin', color: 'bg-orange-100 text-orange-700' },
  { value: 'partner', label: 'Partner', color: 'bg-blue-100 text-blue-700' },
  { value: 'user', label: 'User', color: 'bg-gray-100 text-gray-600' },
];

const COMPANY_ROLES: { value: CompanyRole; label: string; color: string }[] = [
  { value: 'owner', label: 'Owner', color: 'bg-purple-100 text-purple-700' },
  { value: 'admin', label: 'Admin', color: 'bg-indigo-100 text-indigo-700' },
  { value: 'manager', label: 'Manager', color: 'bg-emerald-100 text-emerald-700' },
  { value: 'rep', label: 'Rep', color: 'bg-amber-100 text-amber-700' },
  { value: 'viewer', label: 'Viewer', color: 'bg-slate-100 text-slate-600' },
];

const ROLE_FILTER_OPTIONS: { value: string; label: string }[] = [
  { value: '', label: 'All Roles' },
  { value: 'super_admin', label: 'Super Admin' },
  { value: 'admin', label: 'Admin' },
  { value: 'partner', label: 'Partner' },
  { value: 'user', label: 'User' },
];

function RoleBadge({ role }: { role: string }) {
  const config = PLATFORM_ROLES.find((r) => r.value === role);
  return (
    <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${config?.color || 'bg-gray-100 text-gray-600'}`}>
      {config?.label || role}
    </span>
  );
}

function PlatformRoleDropdown({ userId, currentRole, onRoleChange }: { userId: number; currentRole: string; onRoleChange: (userId: number, newRole: PlatformRole) => void }) {
  const [open, setOpen] = useState(false);
  const [rect, setRect] = useState<DOMRect | null>(null);
  const triggerRef = useRef<HTMLButtonElement>(null);
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: ({ userId, role }: { userId: number; role: PlatformRole }) => adminApi.updateUserRole(userId, role),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-users'] });
      setOpen(false);
    },
  });

  useEffect(() => {
    if (open && triggerRef.current) {
      setRect(triggerRef.current.getBoundingClientRect());
    }
  }, [open]);

  const handleChange = (newRole: PlatformRole) => {
    if (newRole === currentRole) return;
    onRoleChange(userId, newRole);
    mutation.mutate({ userId, role: newRole });
  };

  const config = PLATFORM_ROLES.find((r) => r.value === currentRole);

  const dropdownContent = (
    <div className="w-40 rounded-lg border border-surface-200 bg-white shadow-lg py-1" style={{ position: 'fixed', top: rect ? rect.bottom + 4 : 0, left: rect ? rect.right - 160 : 0, zIndex: 100 }}>
      {PLATFORM_ROLES.map((role) => (
        <button
          key={role.value}
          onClick={() => handleChange(role.value)}
          className="flex w-full items-center gap-2 px-3 py-2 text-sm hover:bg-surface-50"
        >
          {currentRole === role.value && <Check className="h-3.5 w-3.5 text-brand-600" />}
          <span className={currentRole === role.value ? 'text-brand-700 font-medium' : 'text-surface-700'}>
            {role.label}
          </span>
        </button>
      ))}
    </div>
  );

  return (
    <div className="relative">
      <button
        ref={triggerRef}
        onClick={() => setOpen(!open)}
        disabled={mutation.isPending}
        className="inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium hover:opacity-80 disabled:opacity-50 min-w-[80px] justify-center"
      >
        {mutation.isPending ? (
          <Loader2 className="h-3 w-3 animate-spin" />
        ) : (
          <>
            <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${config?.color || 'bg-gray-100 text-gray-600'}`}>
              {config?.label || currentRole}
            </span>
            <ChevronDown className="h-3 w-3 text-surface-400" />
          </>
        )}
      </button>
      {open && (
        <>
          <div className="fixed inset-0 z-[99]" onClick={() => setOpen(false)} />
          {createPortal(dropdownContent, document.body)}
        </>
      )}
    </div>
  );
}

function CompanyRoleDropdown({ userId, currentRole, onRoleChange }: { userId: number; currentRole: string | null; onRoleChange: (userId: number, newRole: CompanyRole, companyId?: number) => void }) {
  const [open, setOpen] = useState(false);
  const [rect, setRect] = useState<DOMRect | null>(null);
  const triggerRef = useRef<HTMLButtonElement>(null);
  const queryClient = useQueryClient();

  // Fetch companies when currentRole is null (need to assign one)
  const { data: companiesData } = useQuery<PaginatedResponse<Organization>>({
    queryKey: ['admin-organizations'],
    queryFn: adminApi.getOrganizations,
    enabled: !currentRole && open,
  });

  const mutation = useMutation({
    mutationFn: ({ userId, role, companyId }: { userId: number; role: CompanyRole; companyId?: number }) => adminApi.updateCompanyRole(userId, role, companyId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-users'] });
      setOpen(false);
    },
  });

  useEffect(() => {
    if (open && triggerRef.current) {
      setRect(triggerRef.current.getBoundingClientRect());
    }
  }, [open]);

  const handleChange = (newRole: CompanyRole, companyId?: number) => {
    if (newRole === currentRole && !companyId) return;
    onRoleChange(userId, newRole, companyId);
    mutation.mutate({ userId, role: newRole, companyId });
  };

  const config = COMPANY_ROLES.find((r) => r.value === currentRole);

  // No company — show assignment dropdown with company picker
  if (!currentRole) {
    const companies = companiesData?.items || [];

    return (
      <div className="relative">
        <button
          ref={triggerRef}
          onClick={() => setOpen(!open)}
          disabled={companies.length === 0 && !companiesData}
          className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium bg-brand-50 text-brand-700 hover:bg-brand-100 border border-brand-200 transition-colors"
        >
          <Building2 className="h-3 w-3" />
          Assign Company
          <ChevronDown className="h-3 w-3" />
        </button>
        {open && companies.length > 0 && (
          <>
            <div className="fixed inset-0 z-[99]" onClick={() => setOpen(false)} />
            {createPortal(
              <div className="w-64 rounded-lg border border-surface-200 bg-white shadow-lg py-1" style={{ position: 'fixed', top: rect ? rect.bottom + 4 : 0, left: rect ? rect.left : 0, zIndex: 100 }}>
                <p className="px-3 py-1.5 text-xs font-semibold text-surface-500 uppercase tracking-wide">Select Company & Role</p>
                {companies.map((company) => (
                  <div key={company.id} className="border-t border-surface-100">
                    <p className="px-3 py-1 text-xs font-medium text-surface-700">{company.name}</p>
                    {COMPANY_ROLES.map((role) => (
                      <button
                        key={role.value}
                        onClick={() => handleChange(role.value, company.id)}
                        className="flex w-full items-center gap-2 px-3 py-1.5 text-sm hover:bg-surface-50"
                      >
                        <span className={`rounded px-1.5 py-0.5 text-xs ${role.color}`}>
                          {role.label}
                        </span>
                      </button>
                    ))}
                  </div>
                ))}
              </div>,
              document.body
            )}
          </>
        )}
      </div>
    );
  }

  const dropdownContent = (
    <div className="w-40 rounded-lg border border-surface-200 bg-white shadow-lg py-1" style={{ position: 'fixed', top: rect ? rect.bottom + 4 : 0, left: rect ? rect.right - 160 : 0, zIndex: 100 }}>
      {COMPANY_ROLES.map((role) => (
        <button
          key={role.value}
          onClick={() => handleChange(role.value)}
          className="flex w-full items-center gap-2 px-3 py-2 text-sm hover:bg-surface-50"
        >
          {currentRole === role.value && <Check className="h-3.5 w-3.5 text-brand-600" />}
          <span className={currentRole === role.value ? 'text-brand-700 font-medium' : 'text-surface-700'}>
            {role.label}
          </span>
        </button>
      ))}
    </div>
  );

  return (
    <div className="relative">
      <button
        ref={triggerRef}
        onClick={() => setOpen(!open)}
        disabled={mutation.isPending}
        className="inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium hover:opacity-80 disabled:opacity-50 min-w-[80px] justify-center"
      >
        {mutation.isPending ? (
          <Loader2 className="h-3 w-3 animate-spin" />
        ) : (
          <>
            <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${config?.color || 'bg-gray-100 text-gray-600'}`}>
              {config?.label || currentRole}
            </span>
            <ChevronDown className="h-3 w-3 text-surface-400" />
          </>
        )}
      </button>
      {open && (
        <>
          <div className="fixed inset-0 z-[99]" onClick={() => setOpen(false)} />
          {createPortal(dropdownContent, document.body)}
        </>
      )}
    </div>
  );
}

export function UsersPage() {
  const [search, setSearch] = useState('');
  const [roleFilter, setRoleFilter] = useState<string>('');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState<number | null>(null);
  const { user: currentUser } = useAuth();
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['admin-users', roleFilter],
    queryFn: () => adminApi.getUsers({ role: roleFilter || undefined }),
  });

  const users = data?.items ?? [];

  const filtered = users.filter((user) =>
    user.email.toLowerCase().includes(search.toLowerCase()) ||
    user.fullName.toLowerCase().includes(search.toLowerCase())
  );

  // Delete mutation
  const deleteMutation = useMutation({
    mutationFn: (userId: number) => adminApi.deleteUser(userId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-users'] });
      setDeleteConfirm(null);
    },
  });

  // Create mutation
  const createMutation = useMutation({
    mutationFn: (data: { email: string; full_name?: string; password: string; role?: PlatformRole; company_name?: string; company_role?: CompanyRole }) =>
      adminApi.createUser(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-users'] });
      setShowCreateModal(false);
    },
  });

  const handlePlatformRoleChange = useCallback((_userId: number, _newRole: PlatformRole) => {
    // Mutation in PlatformRoleDropdown handles the actual API call
  }, []);

  const handleCompanyRoleChange = useCallback((_userId: number, _newRole: CompanyRole, _companyId?: number) => {
    // Mutation in CompanyRoleDropdown handles the actual API call
  }, []);

  if (isLoading) {
    return (
      <AppLayout title="Users">
        <PageLoader />
      </AppLayout>
    );
  }

  return (
    <AppLayout title="Users">
      {/* Header */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-xl sm:text-2xl font-bold text-surface-900">Users</h1>
          <p className="mt-1 text-sm text-surface-500">
            {users.length} user{users.length !== 1 ? 's' : ''} in the system
          </p>
        </div>
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
          <div className="flex gap-2">
            <select
              value={roleFilter}
              onChange={(e) => setRoleFilter(e.target.value)}
              className="rounded-lg border border-surface-300 py-2.5 px-3 text-sm outline-none focus:border-brand-500 min-h-[44px] w-full sm:w-40"
            >
              {ROLE_FILTER_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>{opt.label}</option>
              ))}
            </select>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-surface-500" />
              <input
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Search users..."
                className="w-full border border-surface-300 pl-9 pr-3 py-2.5 text-sm rounded-lg outline-none focus:border-brand-500 min-h-[44px] w-full sm:w-56"
              />
            </div>
          </div>
          <button
            onClick={() => setShowCreateModal(true)}
            className="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-700 min-h-[44px] w-full sm:w-auto"
          >
            <Plus className="h-4 w-4" />
            Add User
          </button>
        </div>
      </div>

      {/* Users Table */}
      {filtered.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-xl border border-surface-200 bg-white py-16">
          <UserIcon className="h-12 w-12 text-surface-300" />
          <p className="mt-4 text-sm font-medium text-surface-700">
            {search || roleFilter ? 'No users match your filters' : 'No users yet'}
          </p>
        </div>
      ) : (
        <div className="rounded-xl border border-surface-200 bg-white">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-surface-200">
                  <th className="pb-3 pl-5 text-left font-medium text-surface-500">User</th>
                  <th className="pb-3 text-left font-medium text-surface-500">Platform Role</th>
                  <th className="pb-3 text-left font-medium text-surface-500">Company Role</th>
                  <th className="pb-3 text-left font-medium text-surface-500">Status</th>
                  <th className="pb-3 text-right font-medium text-surface-500 pr-2">Last Login</th>
                  <th className="pb-3 pr-5 w-10"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-surface-100">
                {filtered.map((user) => (
                  <tr key={user.id} className="hover:bg-surface-50">
                    <td className="py-3 pl-5">
                      <div className="flex items-center gap-3">
                        <div className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-brand-100 text-xs font-semibold text-brand-700">
                          {user.fullName.charAt(0).toUpperCase()}
                        </div>
                        <div className="min-w-0 flex-1">
                          <p className="text-sm font-medium text-surface-900 truncate">{user.fullName}</p>
                          <p className="text-xs text-surface-500 truncate">{user.email}</p>
                        </div>
                      </div>
                    </td>
                    <td className="py-3">
                      <PlatformRoleDropdown
                        userId={user.id}
                        currentRole={user.role}
                        onRoleChange={handlePlatformRoleChange}
                      />
                    </td>
                    <td className="py-3">
                      <CompanyRoleDropdown
                        userId={user.id}
                        currentRole={user.companyRole ?? null}
                        onRoleChange={handleCompanyRoleChange}
                      />
                    </td>
                    <td className="py-3">
                      <span
                        className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
                          user.status === 'active'
                            ? 'bg-success/10 text-success'
                            : 'bg-surface-200 text-surface-600'
                        }`}
                      >
                        {user.status}
                      </span>
                    </td>
                    <td className="py-3 text-right text-surface-500 pr-2">
                      {user.lastLogin ? new Date(user.lastLogin).toLocaleDateString() : 'Never'}
                    </td>
                    <td className="py-3 pr-5 text-right">
                      {user.id !== currentUser?.id && (
                        <button
                          onClick={() => setDeleteConfirm(user.id)}
                          className="inline-flex items-center justify-center rounded-md p-1.5 text-surface-400 hover:text-red-600 hover:bg-red-50 transition-colors"
                          title="Delete user"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Create User Modal */}
      {showCreateModal && (
        <CreateUserModal
          onClose={() => setShowCreateModal(false)}
          onCreate={createMutation.mutate}
          isPending={createMutation.isPending}
        />
      )}

      {/* Delete Confirmation Modal */}
      {deleteConfirm && (
        <DeleteConfirmModal
          user={filtered.find(u => u.id === deleteConfirm)!}
          onConfirm={() => deleteMutation.mutate(deleteConfirm!)}
          onClose={() => setDeleteConfirm(null)}
          isPending={deleteMutation.isPending}
        />
      )}
    </AppLayout>
  );
}

function CreateUserModal({ onClose, onCreate, isPending }: {
  onClose: () => void;
  onCreate: (data: { email: string; full_name?: string; password: string; role?: PlatformRole; company_name?: string; company_role?: CompanyRole }) => void;
  isPending: boolean;
}) {
  const [email, setEmail] = useState('');
  const [fullName, setFullName] = useState('');
  const [password, setPassword] = useState('');
  const [role, setRole] = useState<PlatformRole>('user');
  const [companyName, setCompanyName] = useState('');
  const [companyRole, setCompanyRole] = useState<CompanyRole>('member');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onCreate({ email, full_name: fullName, password, role, company_name: companyName, company_role: companyName ? companyRole : undefined });
  };

  return createPortal(
    <div className="fixed inset-0 z-[200] flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative w-full max-w-md rounded-xl bg-white shadow-xl">
        <div className="flex items-center justify-between border-b border-surface-200 p-5">
          <h2 className="text-lg font-semibold text-surface-900">Add User</h2>
          <button onClick={onClose} className="rounded-md p-1 text-surface-400 hover:text-surface-600">
            <X className="h-5 w-5" />
          </button>
        </div>
        <form onSubmit={handleSubmit} className="p-5 space-y-4">
          <div>
            <label className="block text-sm font-medium text-surface-700 mb-1">Email *</label>
            <input
              type="email"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full rounded-lg border border-surface-300 px-3 py-2 text-sm outline-none focus:border-brand-500"
              placeholder="user@example.com"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-surface-700 mb-1">Full Name</label>
            <input
              type="text"
              value={fullName}
              onChange={(e) => setFullName(e.target.value)}
              className="w-full rounded-lg border border-surface-300 px-3 py-2 text-sm outline-none focus:border-brand-500"
              placeholder="John Doe"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-surface-700 mb-1">Password *</label>
            <input
              type="password"
              required
              minLength={8}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full rounded-lg border border-surface-300 px-3 py-2 text-sm outline-none focus:border-brand-500"
              placeholder="Min 8 characters"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-surface-700 mb-1">Platform Role</label>
            <select
              value={role}
              onChange={(e) => setRole(e.target.value as PlatformRole)}
              className="w-full rounded-lg border border-surface-300 px-3 py-2 text-sm outline-none focus:border-brand-500"
            >
              {PLATFORM_ROLES.map((r) => (
                <option key={r.value} value={r.value}>{r.label}</option>
              ))}
            </select>
          </div>
          <div className="border-t border-surface-200 pt-4 space-y-3">
            <p className="text-xs font-medium text-surface-500 uppercase tracking-wide">Company (optional)</p>
            <div>
              <label className="block text-sm font-medium text-surface-700 mb-1">Company Name</label>
              <input
                type="text"
                value={companyName}
                onChange={(e) => setCompanyName(e.target.value)}
                className="w-full rounded-lg border border-surface-300 px-3 py-2 text-sm outline-none focus:border-brand-500"
                placeholder="Acme Corp"
              />
            </div>
            {companyName && (
              <div>
                <label className="block text-sm font-medium text-surface-700 mb-1">Company Role</label>
                <select
                  value={companyRole}
                  onChange={(e) => setCompanyRole(e.target.value as CompanyRole)}
                  className="w-full rounded-lg border border-surface-300 px-3 py-2 text-sm outline-none focus:border-brand-500"
                >
                  {COMPANY_ROLES.map((r) => (
                    <option key={r.value} value={r.value}>{r.label}</option>
                  ))}
                  <option value="member">Member</option>
                </select>
              </div>
            )}
          </div>
          <div className="flex gap-3 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 rounded-lg border border-surface-300 px-4 py-2.5 text-sm font-medium text-surface-700 hover:bg-surface-50 min-h-[44px]"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isPending}
              className="flex-1 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50 min-h-[44px]"
            >
              {isPending ? <Loader2 className="h-4 w-4 animate-spin mx-auto" /> : 'Create User'}
            </button>
          </div>
        </form>
      </div>
    </div>,
    document.body
  );
}

function DeleteConfirmModal({ user, onConfirm, onClose, isPending }: {
  user: ApiUser;
  onConfirm: () => void;
  onClose: () => void;
  isPending: boolean;
}) {
  return createPortal(
    <div className="fixed inset-0 z-[200] flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative w-full max-w-sm rounded-xl bg-white shadow-xl p-6 text-center">
        <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-red-100">
          <AlertTriangle className="h-6 w-6 text-red-600" />
        </div>
        <h3 className="text-lg font-semibold text-surface-900 mb-2">Delete User</h3>
        <p className="text-sm text-surface-500 mb-6">
          Are you sure you want to delete <strong className="text-surface-700">{user.fullName}</strong> ({user.email})? This action cannot be undone.
        </p>
        <div className="flex gap-3">
          <button
            onClick={onClose}
            disabled={isPending}
            className="flex-1 rounded-lg border border-surface-300 px-4 py-2.5 text-sm font-medium text-surface-700 hover:bg-surface-50 disabled:opacity-50 min-h-[44px]"
          >
            Cancel
          </button>
          <button
            onClick={onConfirm}
            disabled={isPending}
            className="flex-1 rounded-lg bg-red-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-red-700 disabled:opacity-50 min-h-[44px]"
          >
            {isPending ? <Loader2 className="h-4 w-4 animate-spin mx-auto" /> : 'Delete'}
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
}
