'use client';

import { Check, ChevronDown, Eye, Mail, Minus, Package, Send, ShieldCheck, UserCheck, UserPlus, UserX } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';

import { FormField } from '@/components/forms/form-field';
import { MailSentIllustration } from '@/components/illustrations';
import { PageTitle } from '@/components/layout/page-header';
import { SectionCard } from '@/components/settings/section-card';
import { Avatar } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Radio } from '@/components/ui/choice';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Input, Select } from '@/components/ui/input';
import { Menu, type MenuItem } from '@/components/ui/menu';
import { Modal } from '@/components/ui/overlay';
import { ErrorState, ForbiddenState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip } from '@/components/ui/tooltip';
import { ApiError, api } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import { formatRelative } from '@/lib/shipments';
import { cn } from '@/lib/utils';
import { usePermission } from '@/hooks/use-permission';
import { ROLE_PERMISSIONS } from '@/shared/permissions';

interface Member {
  id: string;
  name: string;
  email: string;
  role: 'OWNER' | 'ADMIN' | 'MEMBER' | 'VIEWER';
  disabledAt?: string | null;
  lastLoginAt?: string;
}

interface Invitation {
  id: string;
  email: string;
  role: string;
  invitedById: string;
  expiresAt: string;
  acceptedAt?: string;
  revokedAt?: string;
}

/** The API sends disabledAt: null for active members; older payloads omit it. */
const isActive = (member: Member): boolean => member.disabledAt === undefined || member.disabledAt === null;

export default function TeamSettingsPage() {
  const allowed = usePermission('team:manage');
  const { user } = useAuth();
  const [members, setMembers] = useState<Member[] | null>(null);
  const [invites, setInvites] = useState<Invitation[]>([]);
  const [error, setError] = useState<ApiError | null>(null);
  const [inviteOpen, setInviteOpen] = useState(false);
  const [inviteEmail, setInviteEmail] = useState('');
  const [inviteRole, setInviteRole] = useState<'ADMIN' | 'MEMBER' | 'VIEWER'>('MEMBER');
  const [inviteError, setInviteError] = useState<string | null>(null);
  const [confirm, setConfirm] = useState<{ title: string; message: string; confirmLabel?: string; destructive?: boolean; action: () => Promise<void> } | null>(null);
  const [matrixOpen, setMatrixOpen] = useState(false);
  // Snapshot of "now" for expiry chips; stable across re-renders.
  const [now] = useState(() => Date.now());

  const reload = () => {
    void Promise.all([api<Member[]>('/team/members'), api<Invitation[]>('/team/invitations')])
      .then(([nextMembers, nextInvites]) => {
        setMembers(nextMembers);
        setInvites(nextInvites.filter((invite) => invite.acceptedAt === undefined && invite.revokedAt === undefined));
      })
      .catch((reason: unknown) => setError(reason instanceof ApiError ? reason : null));
  };

  useEffect(() => {
    if (!allowed) return;
    reload();
  }, [allowed]);

  if (!allowed) return <ForbiddenState />;
  if (error !== null) return <ErrorState message={error.message} requestId={error.requestId} onRetry={reload} />;
  if (members === null) {
    return (
      <div className="grid gap-6" aria-hidden="true">
        <Skeleton className="h-72 rounded-xl" />
        <Skeleton className="h-40 rounded-xl" />
      </div>
    );
  }

  const ownerCount = members.filter((member) => member.role === 'OWNER' && isActive(member)).length;

  const canChangeRole = (member: Member) => {
    if (user === null) return false;
    if (member.id === user.id) return false;
    if (user.role === 'ADMIN' && member.role === 'OWNER') return false;
    return true;
  };

  /** Explains why a member's controls are disabled (the server enforces the same rules). */
  const guardReason = (member: Member): string | null => {
    if (user === null) return 'Sign in again to manage the team.';
    if (member.id === user.id) return 'You cannot change your own role or access.';
    if (user.role === 'ADMIN' && member.role === 'OWNER') return 'Admins cannot change an owner.';
    if (member.role === 'OWNER' && ownerCount <= 1) return 'The last owner cannot be changed.';
    return null;
  };

  const roleSelect = (member: Member) => {
    const reason = guardReason(member);
    const disabled = !canChangeRole(member) || reason !== null;
    const select = (
      <Select
        aria-label={`Role for ${member.name}`}
        value={member.role}
        disabled={disabled}
        className="h-8 min-h-8 w-[7.5rem] rounded-pill border-border bg-surface-muted py-0 pl-3 text-small font-semibold"
        onChange={(event) => {
          const role = event.target.value as Member['role'];
          setConfirm({
            title: 'Change role?',
            message: `Change ${member.name} to ${roleLabel(role)}. Their access updates immediately.`,
            confirmLabel: 'Change role',
            destructive: false,
            action: async () => {
              await api(`/team/members/${member.id}`, { method: 'PATCH', json: { role } });
              toast.success('Role updated.');
              reload();
            },
          });
        }}
      >
        {(['OWNER', 'ADMIN', 'MEMBER', 'VIEWER'] as const).map((role) => (
          <option key={role} value={role}>
            {roleLabel(role)}
          </option>
        ))}
      </Select>
    );
    return disabled && reason !== null ? (
      <Tooltip label={reason}>
        <span tabIndex={0} className="rounded-pill">
          {select}
        </span>
      </Tooltip>
    ) : (
      select
    );
  };

  const memberMenu = (member: Member): MenuItem[] => {
    const reason = guardReason(member) ?? undefined;
    const disabled = !canChangeRole(member) || reason !== undefined;
    return isActive(member)
      ? [
          {
            label: 'Disable access',
            icon: UserX,
            danger: true,
            disabled,
            disabledReason: reason,
            onSelect: () =>
              setConfirm({
                title: 'Disable this member?',
                message: `${member.name} will lose access immediately. You can enable them again later.`,
                confirmLabel: 'Disable member',
                destructive: true,
                action: async () => {
                  await api(`/team/members/${member.id}`, { method: 'DELETE' });
                  toast.success('Member disabled.');
                  reload();
                },
              }),
          },
        ]
      : [
          {
            label: 'Enable access',
            icon: UserCheck,
            disabled,
            disabledReason: reason,
            onSelect: () =>
              setConfirm({
                title: 'Enable this member?',
                message: `${member.name} will regain access with the ${roleLabel(member.role)} role.`,
                confirmLabel: 'Enable member',
                destructive: false,
                action: async () => {
                  await api(`/team/members/${member.id}`, { method: 'PATCH', json: { enabled: true } });
                  toast.success('Member enabled.');
                  reload();
                },
              }),
          },
        ];
  };

  const statusBadge = (member: Member) =>
    isActive(member) ? (
      <span className="inline-flex items-center gap-1.5 rounded-pill bg-success-soft px-2.5 py-0.5 text-caption font-semibold text-success">
        <span className="h-1.5 w-1.5 rounded-full bg-success" aria-hidden="true" />
        Active
      </span>
    ) : (
      <span className="inline-flex items-center gap-1.5 rounded-pill bg-surface-muted px-2.5 py-0.5 text-caption font-semibold text-muted-foreground">
        <span className="h-1.5 w-1.5 rounded-full bg-subtle-foreground" aria-hidden="true" />
        Disabled
      </span>
    );

  const permissions = [...new Set(Object.values(ROLE_PERMISSIONS).flat())];

  return (
    <div className="grid gap-6">
      <PageTitle title="Team" breadcrumb="Settings" />
      <SectionCard
        title="Members"
        description={`${members.length} ${members.length === 1 ? 'person' : 'people'} in this workspace.`}
        action={
          <Button
            type="button"
            size="sm"
            onClick={() => {
              setInviteError(null);
              setInviteOpen(true);
            }}
          >
            <UserPlus className="h-4 w-4" aria-hidden="true" />
            Invite member
          </Button>
        }
      >
        {/* Desktop table */}
        <div className="-mx-5 hidden overflow-x-auto md:-mx-6 md:block">
          <table className="w-full min-w-[640px] text-left text-small">
            <thead>
              <tr className="h-10 border-y border-border bg-surface-muted/70 text-caption font-semibold uppercase tracking-[0.08em] text-muted-foreground">
                <th scope="col" className="pl-6 pr-3 font-semibold">Member</th>
                <th scope="col" className="px-3 font-semibold">Role</th>
                <th scope="col" className="px-3 font-semibold">Status</th>
                <th scope="col" className="px-3 font-semibold">Last login</th>
                <th scope="col" className="w-12 pr-4">
                  <span className="sr-only">Actions</span>
                </th>
              </tr>
            </thead>
            <tbody>
              {members.map((member) => (
                <tr key={member.id} className="h-16 border-b border-border last:border-b-0">
                  <td className="pl-6 pr-3">
                    <span className="flex items-center gap-3">
                      <Avatar name={member.name} size="md" />
                      <span className="min-w-0">
                        <span className="flex items-center gap-2 font-semibold text-foreground">
                          <span className="truncate">{member.name}</span>
                          {member.id === user?.id ? <span className="rounded-pill bg-primary-soft px-1.5 text-[10px] font-bold uppercase leading-4 text-primary">You</span> : null}
                        </span>
                        <span className="block truncate text-caption text-muted-foreground">{member.email}</span>
                      </span>
                    </span>
                  </td>
                  <td className="px-3">{roleSelect(member)}</td>
                  <td className="px-3">{statusBadge(member)}</td>
                  <td className="whitespace-nowrap px-3 text-muted-foreground">{member.lastLoginAt === undefined ? 'Never' : formatRelative(member.lastLoginAt)}</td>
                  <td className="pr-4">
                    <Menu items={memberMenu(member)} label={`Actions for ${member.name}`} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {/* Mobile cards */}
        <ul className="grid gap-3 md:hidden">
          {members.map((member) => (
            <li key={member.id} className="rounded-lg border border-border p-3">
              <div className="flex items-start gap-3">
                <Avatar name={member.name} size="md" />
                <div className="min-w-0 flex-1">
                  <p className="flex items-center gap-2 text-small font-semibold">
                    <span className="truncate">{member.name}</span>
                    {member.id === user?.id ? <span className="rounded-pill bg-primary-soft px-1.5 text-[10px] font-bold uppercase leading-4 text-primary">You</span> : null}
                  </p>
                  <p className="truncate text-caption text-muted-foreground">{member.email}</p>
                </div>
                <Menu items={memberMenu(member)} label={`Actions for ${member.name}`} />
              </div>
              <div className="mt-3 flex flex-wrap items-center gap-2">
                {roleSelect(member)}
                {statusBadge(member)}
                <span className="ml-auto text-caption text-muted-foreground">{member.lastLoginAt === undefined ? 'Never signed in' : formatRelative(member.lastLoginAt)}</span>
              </div>
            </li>
          ))}
        </ul>
      </SectionCard>

      <SectionCard title="Pending invitations" description="Invitations expire after a few days. Resend to extend them.">
        {invites.length === 0 ? (
          <div className="grid justify-items-center gap-2 py-4 text-center">
            <MailSentIllustration size={72} />
            <p className="text-small font-semibold">No pending invitations</p>
            <p className="text-caption text-muted-foreground">Invite teammates to share the wallet and address book.</p>
          </div>
        ) : (
          <ul className="-mx-2 grid gap-1">
            {invites.map((invite) => {
              const days = Math.ceil((Date.parse(invite.expiresAt) - now) / 86_400_000);
              const inviter = members.find((member) => member.id === invite.invitedById)?.name;
              return (
                <li key={invite.id} className="flex flex-wrap items-center gap-3 rounded-lg px-2 py-2.5 hover:bg-surface-muted/60">
                  <span className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-surface-muted text-muted-foreground">
                    <Mail className="h-4 w-4" aria-hidden="true" />
                  </span>
                  <div className="min-w-0 flex-1">
                    <p className="flex flex-wrap items-center gap-2 text-small font-semibold">
                      <span className="truncate">{invite.email}</span>
                      <span className="rounded-pill bg-primary-soft px-2 py-0.5 text-[11px] font-semibold text-primary">{roleLabel(invite.role)}</span>
                    </p>
                    <p className="text-caption text-muted-foreground">{inviter === undefined ? 'Invited' : `Invited by ${inviter}`}</p>
                  </div>
                  <span
                    className={cn(
                      'rounded-pill px-2.5 py-0.5 text-caption font-semibold tabular-nums',
                      days <= 1 ? 'bg-warning-soft text-warning' : 'bg-surface-muted text-muted-foreground',
                    )}
                    title={new Date(invite.expiresAt).toLocaleString()}
                  >
                    {days <= 0 ? 'Expired' : `Expires in ${days} ${days === 1 ? 'day' : 'days'}`}
                  </span>
                  <div className="flex gap-1">
                    <Button
                      type="button"
                      size="sm"
                      variant="ghost"
                      onClick={() => {
                        void api(`/team/invitations/${invite.id}/resend`, { method: 'POST' })
                          .then(() => toast.success('Invitation resent.'))
                          .catch((reason: unknown) => toast.error(reason instanceof ApiError ? reason.message : 'Could not resend.'));
                      }}
                    >
                      Resend
                    </Button>
                    <Button
                      type="button"
                      size="sm"
                      variant="ghost"
                      className="text-danger hover:bg-danger-soft"
                      onClick={() => {
                        void api(`/team/invitations/${invite.id}`, { method: 'DELETE' })
                          .then(() => {
                            toast.success('Invitation revoked.');
                            reload();
                          })
                          .catch((reason: unknown) => toast.error(reason instanceof ApiError ? reason.message : 'Could not revoke.'));
                      }}
                    >
                      Revoke
                    </Button>
                  </div>
                </li>
              );
            })}
          </ul>
        )}
      </SectionCard>

      <SectionCard
        title="Roles and permissions"
        description="What each role can do in this workspace."
        action={
          <Button type="button" variant="ghost" size="sm" aria-expanded={matrixOpen} onClick={() => setMatrixOpen((value) => !value)}>
            {matrixOpen ? 'Hide' : 'Show'} matrix
            <ChevronDown className={cn('h-4 w-4 transition-transform', matrixOpen && 'rotate-180')} aria-hidden="true" />
          </Button>
        }
      >
        {matrixOpen ? (
          <div className="-mx-5 overflow-x-auto md:-mx-6">
            <table className="w-full min-w-[560px] text-left text-small">
              <thead>
                <tr className="h-10 border-y border-border bg-surface-muted/70 text-caption font-semibold uppercase tracking-[0.08em] text-muted-foreground">
                  <th scope="col" className="sticky left-0 z-[1] bg-surface-muted pl-6 pr-3 font-semibold">Permission</th>
                  {(['OWNER', 'ADMIN', 'MEMBER', 'VIEWER'] as const).map((role) => (
                    <th key={role} scope="col" className="px-3 text-center font-semibold">
                      {roleLabel(role)}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {permissions.map((permission) => (
                  <tr key={permission} className="border-b border-border last:border-b-0">
                    <th scope="row" className="sticky left-0 z-[1] bg-surface py-2.5 pl-6 pr-3 font-medium text-foreground">
                      {permissionLabel(permission)}
                    </th>
                    {(['OWNER', 'ADMIN', 'MEMBER', 'VIEWER'] as const).map((role) => (
                      <td key={role} className="px-3 text-center">
                        {ROLE_PERMISSIONS[role].includes(permission) ? (
                          <Check className="mx-auto h-4 w-4 text-success" strokeWidth={3} aria-label="Allowed" />
                        ) : (
                          <Minus className="mx-auto h-4 w-4 text-subtle-foreground" aria-label="Not allowed" />
                        )}
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <p className="text-small text-muted-foreground">Owners and admins manage the workspace, members create shipments and viewers have read-only access.</p>
        )}
      </SectionCard>

      <Modal open={inviteOpen} title="Invite a teammate" onClose={() => setInviteOpen(false)}>
        <form
          className="grid gap-5"
          onSubmit={(event) => {
            event.preventDefault();
            setInviteError(null);
            void api('/team/invitations', { method: 'POST', json: { email: inviteEmail, role: inviteRole } })
              .then(() => {
                toast.success('Invitation sent.');
                setInviteOpen(false);
                setInviteEmail('');
                reload();
              })
              .catch((reason: unknown) => setInviteError(reason instanceof ApiError ? reason.message : 'Could not send invitation.'));
          }}
        >
          <FormField id="invite-email" label="Email" error={inviteError ?? undefined}>
            <Input id="invite-email" type="email" required leading={<Mail />} placeholder="teammate@company.com" value={inviteEmail} onChange={(event) => setInviteEmail(event.target.value)} />
          </FormField>
          <fieldset className="grid gap-2">
            <legend className="mb-1.5 text-small font-semibold">Role</legend>
            {INVITE_ROLES.map((option) => (
              <Radio
                key={option.value}
                name="invite-role"
                label={option.label}
                hint={
                  <>
                    {option.description}
                    <span className="mt-1 block text-caption text-subtle-foreground">{option.summary}</span>
                  </>
                }
                icon={<option.icon />}
                checked={inviteRole === option.value}
                onChange={() => setInviteRole(option.value)}
              />
            ))}
          </fieldset>
          <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
            <Button type="button" variant="secondary" onClick={() => setInviteOpen(false)}>
              Cancel
            </Button>
            <Button type="submit">
              <Send className="h-4 w-4" aria-hidden="true" />
              Send invitation
            </Button>
          </div>
        </form>
      </Modal>

      <ConfirmDialog
        open={confirm !== null}
        title={confirm?.title ?? ''}
        message={confirm?.message ?? ''}
        confirmLabel={confirm?.confirmLabel ?? 'Confirm'}
        cancelLabel="Cancel"
        destructive={confirm?.destructive ?? true}
        onClose={() => setConfirm(null)}
        onConfirm={() => {
          if (confirm === null) return;
          void confirm
            .action()
            .catch((reason: unknown) => toast.error(reason instanceof ApiError ? reason.message : 'Action failed.'))
            .finally(() => setConfirm(null));
        }}
      />
    </div>
  );
}

const roleLabel = (role: string): string => role.charAt(0).toUpperCase() + role.slice(1).toLowerCase();

/** "shipments:create" becomes "Create shipments". */
const permissionLabel = (permission: string): string => {
  const [area = '', action = ''] = permission.split(':');
  const verb = action.replaceAll('_', ' ');
  return `${verb.charAt(0).toUpperCase()}${verb.slice(1)} ${area.replaceAll('_', ' ')}`;
};

const INVITE_ROLES = [
  { value: 'ADMIN', label: 'Admin', icon: ShieldCheck, description: 'Manages the team, settings and wallet.', summary: 'Everything except deleting the company.' },
  { value: 'MEMBER', label: 'Member', icon: Package, description: 'Creates shipments and buys labels.', summary: 'Shipments, addresses and tracking.' },
  { value: 'VIEWER', label: 'Viewer', icon: Eye, description: 'Read-only access to shipments and tracking.', summary: 'Cannot spend from the wallet.' },
] as const;
