'use client';

import { useEffect, useMemo, useState } from 'react';
import { Alert, Button, Drawer, Form, Input, Modal, Select, Spin } from 'antd';
import { Icon } from '../ui/Icon';
import { UserAvatar } from '../ui/UserAvatar';
import { ChipTag, KeyValueList, StatusBadge } from '../platform/PlatformPrimitives';
import { fmtDate, relTime } from '../platform/platformFormat';
import type { WorkspaceMember, WorkspaceRouteId } from './workspaceTypes';
import { useAuth, UserRole } from '../../context/AuthContext';
import { isRouteAllowed, rolesApi } from '../../lib/roles';

export function InviteMemberModal(props: { orgName: string; open: boolean; loading: boolean; error: string | null; inviteLink: string | null; invitedEmail: string | null; emailSent: boolean; roles?: Array<{ id: string; name: string; isSystem: boolean }>; onCopyLink: (link: string) => void; onCancel: () => void; onSubmit: (values: { name: string; email: string; roleId?: string; canDelete?: boolean; canExport?: boolean }) => Promise<void> }) {
  if (!props.open) return null;
  return <InviteMemberModalInner {...props} />;
}

function InviteMemberModalInner({
  orgName,
  open,
  loading,
  error,
  inviteLink,
  invitedEmail,
  emailSent,
  roles,
  onCopyLink,
  onCancel,
  onSubmit,
}: {
  orgName: string;
  open: boolean;
  loading: boolean;
  error: string | null;
  inviteLink: string | null;
  invitedEmail: string | null;
  emailSent: boolean;
  roles?: Array<{ id: string; name: string; isSystem: boolean }>;
  onCopyLink: (link: string) => void;
  onCancel: () => void;
  onSubmit: (values: { name: string; email: string; roleId?: string; canDelete?: boolean; canExport?: boolean }) => Promise<void>;
}) {
  const [form] = Form.useForm();
  const [fetchedRoles, setFetchedRoles] = useState<Array<{ id: string; name: string; isSystem: boolean }>>([]);

  useEffect(() => {
    if ((!roles || roles.length === 0) && open) {
      let active = true;
      rolesApi
        .list()
        .then((list) => {
          if (active) setFetchedRoles(list);
        })
        .catch(() => {
          if (active) setFetchedRoles([]);
        });
      return () => {
        active = false;
      };
    }
  }, [open, roles]);

  const availableRoles = useMemo(() => {
    if (roles && roles.length > 0) return roles;
    return fetchedRoles;
  }, [roles, fetchedRoles]);

  return (
    <Modal open={open} title={`Invite team member — ${orgName}`} onCancel={onCancel} footer={null} destroyOnHidden width={500}>
      {invitedEmail ? (
        <div className="flex flex-col gap-4">
          {emailSent ? <Alert type="success" showIcon title={`Invitation emailed to ${invitedEmail}`} description="The link works once and expires in 7 days." /> : <Alert type="warning" showIcon title={`${invitedEmail} was invited, but the email was not sent`} description={inviteLink ? 'Email is not set up in this development environment. Share the one-time link below instead.' : 'Check the SMTP settings, then ask the platform team to resend the invitation.'} />}
          {inviteLink ? (
            <div>
              <div className="mb-1.5 text-[12px] font-medium text-[var(--tcx-muted)]">One-time invitation link</div>
              <div className="flex items-center gap-2">
                <Input value={inviteLink} readOnly className="font-mono text-[12px]" />
                <Button type="primary" icon={<Icon name="copy" size={14} />} onClick={() => onCopyLink(inviteLink)}>
                  Copy
                </Button>
              </div>
            </div>
          ) : null}
          <div className="flex justify-end pt-1">
            <Button type="primary" onClick={onCancel}>
              Done
            </Button>
          </div>
        </div>
      ) : (
        <>
          <p className="mb-4 text-[13.5px] text-[var(--tcx-muted)]">We email them a link to join as a member. The link works once and expires in 7 days.</p>
          {error ? <Alert type="error" showIcon title={error} className="mb-4" /> : null}
          <Form
            form={form}
            preserve={false}
            layout="vertical"
            onFinish={async (vals) => {
              await onSubmit(vals);
            }}
          >
            <Form.Item
              name="name"
              label="Full name"
              rules={[
                { required: true, message: 'Full name is required' },
                { max: 255, message: 'Maximum 255 characters' },
              ]}
            >
              <Input placeholder="Enter full name" autoFocus />
            </Form.Item>
            <Form.Item
              name="email"
              label="Work email"
              rules={[
                { required: true, message: 'Email address is required' },
                { type: 'email', message: 'Enter a valid email address' },
              ]}
            >
              <Input placeholder="Enter email address" />
            </Form.Item>

            <Form.Item name="roleId" label="Assigned Role" rules={[{ required: true, message: 'Please select a role' }]}>
              <Select
                placeholder="Select a role"
                loading={availableRoles.length === 0}
                options={availableRoles.map((r) => ({
                  label: `${r.name}${r.isSystem ? ' (System)' : ''}`,
                  value: r.id,
                }))}
              />
            </Form.Item>

            <div className="mt-5 flex justify-end gap-2">
              <Button onClick={onCancel}>Cancel</Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                Send invitation
              </Button>
            </div>
          </Form>
        </>
      )}
    </Modal>
  );
}

export function MemberDetailDrawer({ open, member, loading, busyMemberId, currentUserId, onClose, onUpdateStatus }: { open: boolean; member: WorkspaceMember | null; loading: boolean; busyMemberId: string | null; currentUserId: string; onClose: () => void; onTogglePermission?: (member: WorkspaceMember, field: 'canDelete' | 'canExport', nextVal: boolean) => Promise<void>; onUpdateStatus: (member: WorkspaceMember, nextStatus: 'ACTIVE' | 'SUSPENDED') => Promise<void> }) {
  const isAdmin = member?.role === UserRole.ORGANIZATION_ADMIN;
  const isSelf = member?.id === currentUserId;
  const isBusy = member ? busyMemberId === member.id : false;

  return (
    <Drawer open={open} size={480} onClose={onClose} destroyOnHidden closable={false} className="tcx-platform-drawer" styles={{ body: { padding: 0 }, header: { display: 'none' } }}>
      {loading && !member ? (
        <div className="flex h-full items-center justify-center p-6">
          <Spin size="large" />
        </div>
      ) : !member ? null : (
        <div className="flex h-full flex-col">
          <div className="border-b border-[var(--tcx-border)] px-6 pt-5 pb-4">
            <div className="flex items-start gap-3.5">
              <UserAvatar name={member.name} size={52} className="tcx-avatar-lg-sq flex-none" />
              <div className="min-w-0 flex-1">
                <h2 className="m-0 truncate text-[19px] font-bold tracking-[-0.015em] text-[var(--tcx-text)]">
                  {member.name}
                  {isSelf ? <span className="ml-2 text-[13px] font-normal text-[var(--tcx-muted)]">(you)</span> : null}
                </h2>
                <p className="mt-0.5 mb-2 truncate text-[13px] text-[var(--tcx-muted)]">{member.email}</p>
                <div className="flex flex-wrap items-center gap-2">
                  <ChipTag>{member.customRole?.name || (isAdmin ? 'Organization Admin' : 'Unassigned')}</ChipTag>
                  <StatusBadge label={member.status} tone={member.status === 'ACTIVE' ? 'green' : member.status === 'INVITED' ? 'amber' : 'red'} />
                </div>
              </div>
              <button type="button" aria-label="Close member drawer" onClick={onClose} className="grid h-8 w-8 flex-none cursor-pointer place-items-center rounded-lg border-0 bg-transparent text-[var(--tcx-muted)] hover:bg-[var(--tcx-sunken)] hover:text-[var(--tcx-text)]">
                <Icon name="x" size={18} />
              </button>
            </div>

            {!isAdmin ? (
              <div className="mt-4 flex flex-wrap items-center gap-2">
                {member.status === 'SUSPENDED' ? (
                  <Button
                    type="primary"
                    size="small"
                    loading={isBusy}
                    onClick={() => {
                      void onUpdateStatus(member, 'ACTIVE');
                    }}
                  >
                    Reactivate member
                  </Button>
                ) : member.status === 'ACTIVE' ? (
                  <Button
                    danger
                    size="small"
                    loading={isBusy}
                    onClick={() => {
                      void onUpdateStatus(member, 'SUSPENDED');
                    }}
                  >
                    Suspend member
                  </Button>
                ) : null}
              </div>
            ) : null}
          </div>

          <div className="flex-1 space-y-6 overflow-y-auto px-6 py-5">
            <section>
              <h3 className="mb-2 text-[12px] font-bold uppercase tracking-[0.06em] text-[var(--tcx-muted)]">Account details</h3>
              <KeyValueList
                rows={[
                  { label: 'Email', value: member.email },
                  {
                    label: 'Role',
                    value: member.customRole?.name || (isAdmin ? 'Organization Admin' : 'Standard Member'),
                  },
                  {
                    label: 'Last sign-in',
                    value: member.lastLoginAt ? relTime(member.lastLoginAt) : 'Never signed in',
                  },
                  { label: 'Added', value: fmtDate(member.createdAt) },
                ]}
              />
            </section>
          </div>
        </div>
      )}
    </Drawer>
  );
}

export function WorkspaceCommandPaletteModal({ open, isAdmin, members, onClose, onNavigate, onSelectMember, onOpenInviteModal }: { open: boolean; isAdmin: boolean; members: WorkspaceMember[]; onClose: () => void; onNavigate: (route: WorkspaceRouteId) => void; onSelectMember: (memberId: string) => void; onOpenInviteModal: () => void }) {
  const { user } = useAuth();
  const [query, setQuery] = useState('');

  const navItems = useMemo(() => {
    const items: Array<{
      route: WorkspaceRouteId;
      label: string;
      icon: 'dashboard' | 'leads' | 'contacts' | 'building' | 'deals' | 'pipeline' | 'projects' | 'clock' | 'user' | 'shield' | 'palette' | 'package' | 'quote' | 'receipt' | 'reports' | 'database';
    }> = [
      { route: 'overview', label: 'Overview', icon: 'dashboard' },
      { route: 'leads', label: 'Leads', icon: 'leads' },
      { route: 'contacts', label: 'Contacts', icon: 'contacts' },
      { route: 'accounts', label: 'Accounts', icon: 'building' },
      { route: 'deals', label: 'Deals', icon: 'deals' },
      { route: 'pipeline', label: 'Pipeline', icon: 'pipeline' },
      { route: 'projects', label: 'Projects', icon: 'projects' },
      { route: 'services', label: 'Services', icon: 'package' },
      { route: 'quotes', label: 'Quotes', icon: 'quote' },
      { route: 'invoices', label: 'Invoices', icon: 'receipt' },
      { route: 'reports', label: 'Reports', icon: 'reports' },
      { route: 'data', label: 'Database Backup', icon: 'database' },
    ];
    if (isAdmin) {
      items.push({ route: 'users', label: 'Users & Teams', icon: 'contacts' }, { route: 'roles', label: 'Roles & Permissions', icon: 'shield' }, { route: 'organization', label: 'Organization', icon: 'building' });
    }
    items.push(
      {
        route: 'account',
        label: 'Your profile',
        icon: 'user',
      },
      {
        route: 'appearance',
        label: 'Appearance & theme',
        icon: 'palette',
      },
    );
    const allowed = items.filter((item) => isRouteAllowed(user, item.route));
    const q = query.trim().toLowerCase();
    return q ? allowed.filter((item) => item.label.toLowerCase().includes(q)) : allowed;
  }, [isAdmin, user, query]);

  const matchingMembers = useMemo(() => {
    if (!isAdmin) return [];
    const q = query.trim().toLowerCase();
    const list = q ? members.filter((m) => m.name.toLowerCase().includes(q) || m.email.toLowerCase().includes(q)) : members;
    return list.slice(0, 6);
  }, [isAdmin, members, query]);

  return (
    <Modal
      open={open}
      onCancel={onClose}
      afterOpenChange={(isOpen) => {
        if (!isOpen) setQuery('');
      }}
      footer={null}
      closable={false}
      destroyOnHidden
      width={540}
      styles={{ body: { padding: 14 } }}
    >
      <Input autoFocus allowClear size="large" prefix={<Icon name="search" size={16} />} placeholder={isAdmin ? 'Jump to view, team member, or invite action…' : 'Jump to workspace views…'} value={query} onChange={(e) => setQuery(e.target.value)} />

      <div className="mt-3 max-h-[360px] space-y-4 overflow-y-auto pr-1">
        {isAdmin ? (
          <div>
            <div className="px-2 pb-1 text-[11px] font-semibold uppercase tracking-[0.06em] text-[var(--tcx-muted)]">Actions</div>
            <button
              type="button"
              onClick={() => {
                onClose();
                onOpenInviteModal();
              }}
              className="flex w-full cursor-pointer items-center gap-3 rounded-xl border-0 bg-transparent px-2.5 py-2 text-left text-[var(--tcx-text)] hover:bg-[var(--tcx-surface-2)]"
            >
              <span className="grid h-8 w-8 flex-none place-items-center rounded-lg bg-[var(--tcx-primary-soft)] text-[var(--tcx-primary)]">
                <Icon name="userPlus" size={16} />
              </span>
              <div className="min-w-0 flex-1">
                <div className="text-[13.5px] font-medium">Invite team member</div>
                <div className="text-[12px] text-[var(--tcx-muted)]">Send a 7-day invitation email and onboarding link</div>
              </div>
            </button>
          </div>
        ) : null}

        {matchingMembers.length > 0 ? (
          <div>
            <div className="px-2 pb-1 text-[11px] font-semibold uppercase tracking-[0.06em] text-[var(--tcx-muted)]">Team members</div>
            <div className="flex flex-col">
              {matchingMembers.map((m) => (
                <button
                  key={m.id}
                  type="button"
                  onClick={() => {
                    onSelectMember(m.id);
                    onClose();
                  }}
                  className="flex w-full cursor-pointer items-center gap-3 rounded-xl border-0 bg-transparent px-2.5 py-2 text-left text-[var(--tcx-text)] hover:bg-[var(--tcx-surface-2)]"
                >
                  <UserAvatar name={m.name} size={28} />
                  <div className="min-w-0 flex-1">
                    <div className="truncate text-[13.5px] font-medium">{m.name}</div>
                    <div className="truncate text-[11.5px] text-[var(--tcx-muted)]">{m.email}</div>
                  </div>
                  <StatusBadge label={m.status} tone={m.status === 'ACTIVE' ? 'green' : m.status === 'INVITED' ? 'amber' : 'red'} />
                </button>
              ))}
            </div>
          </div>
        ) : null}

        {navItems.length > 0 ? (
          <div>
            <div className="px-2 pb-1 text-[11px] font-semibold uppercase tracking-[0.06em] text-[var(--tcx-muted)]">Workspace</div>
            <div className="flex flex-col">
              {navItems.map((item) => (
                <button
                  key={item.route}
                  type="button"
                  onClick={() => {
                    onNavigate(item.route);
                    onClose();
                  }}
                  className="flex w-full cursor-pointer items-center gap-3 rounded-xl border-0 bg-transparent px-2.5 py-2 text-left text-[var(--tcx-text)] hover:bg-[var(--tcx-surface-2)]"
                >
                  <span className="grid h-8 w-8 flex-none place-items-center rounded-lg bg-[var(--tcx-sunken)] text-[var(--tcx-text-2)]">
                    <Icon name={item.icon} size={15} />
                  </span>
                  <div className="min-w-0 flex-1 text-[13.5px] font-medium">{item.label}</div>
                </button>
              ))}
            </div>
          </div>
        ) : null}
      </div>
    </Modal>
  );
}
