'use client';

import Link from 'next/link';
import { useEffect, useState, useTransition } from 'react';
import {
  inviteMemberAction,
  loadOrgTeamStateAction,
  removeMemberAction,
  updateRoleAction,
} from './actions';
import { KPIGrid } from '@/components/kpi-grid';
import { useRegistryWebTelemetry } from '@/components/registry-web-telemetry';
import { useWorkspaceState } from '@/components/workspace-state-provider';

interface Member {
  user_id: string;
  email: string;
  role: string;
  created_at: string;
  display_name?: string | null;
  username?: string | null;
}

interface OrganizationOption {
  id: string;
  slug: string;
  name: string;
  seat_limit: number;
}

interface AuditEntry {
  id: string;
  scope: string;
  action: string;
  target_type: string;
  created_at: string;
}

interface UsageSummary {
  members: number;
  seat_limit: number;
  content_items: number;
  public_packages: number;
  private_packages: number;
  pending_approvals: number;
  api_requests_30d: number;
  org_package_publishes_30d: number;
  approval_actions_30d: number;
}

function UserPlusIcon({ size = 16 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
      <circle cx="8.5" cy="7" r="4" />
      <line x1="20" x2="20" y1="8" y2="14" />
      <line x1="23" x2="17" y1="11" y2="11" />
    </svg>
  );
}

function UsersIcon({ size = 18 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
      <circle cx="9" cy="7" r="4" />
      <path d="M22 21v-2a4 4 0 0 0-3-3.87" />
      <path d="M16 3.13a4 4 0 0 1 0 7.75" />
    </svg>
  );
}

function ActivityIcon({ size = 18 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M22 12h-4l-3 9L9 3l-3 9H2" />
    </svg>
  );
}

function PackageIcon({ size = 18 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="m7.5 4.27 9 5.15" />
      <path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z" />
      <path d="m3.3 7 8.7 5 8.7-5" />
      <path d="M12 22V12" />
    </svg>
  );
}

function MailIcon({ size = 18 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <rect width="20" height="16" x="2" y="4" rx="2" />
      <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7" />
    </svg>
  );
}

function TrashIcon({ size = 14 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M3 6h18" />
      <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" />
      <path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
    </svg>
  );
}

function UsersLgIcon({ size = 48 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
      <circle cx="9" cy="7" r="4" />
      <path d="M22 21v-2a4 4 0 0 0-3-3.87" />
      <path d="M16 3.13a4 4 0 0 1 0 7.75" />
    </svg>
  );
}

function getInitials(name: string): string {
  return name
    .split(/[\s@]/)
    .filter(Boolean)
    .slice(0, 2)
    .map((segment) => segment[0].toUpperCase())
    .join('');
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  });
}

function formatActionLabel(action: string): string {
  return action
    .split('.')
    .map((part) => part.replace(/_/g, ' '))
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(' · ');
}

function TeamMemberRow({
  member,
  onRemove,
  onRoleChange,
  removingId,
}: {
  member: Member;
  onRemove: (userId: string) => void;
  onRoleChange: (userId: string, role: string) => void;
  removingId: string | null;
}) {
  return (
    <div className="registry-team-row">
      <div className="registry-team-row-main">
        <div className="registry-team-avatar" aria-hidden="true">
          <span className="registry-team-avatar-text">
            {getInitials(member.display_name || member.email)}
          </span>
        </div>

        <div className="registry-team-identity">
          <p className="registry-team-name">
            {member.display_name || member.email.split('@')[0]}
          </p>
          <p className="registry-team-email">{member.email}</p>
        </div>
      </div>

      <div className="registry-team-row-trail">
        <span className="d-annotation registry-team-role" data-role={member.role}>
          {member.role}
        </span>

        <span className="registry-team-meta">{formatDate(member.created_at)}</span>

        <div className="registry-team-row-actions">
          <select
            className="d-control registry-team-select"
            defaultValue={member.role}
            disabled={member.role === 'owner'}
            onChange={(event) => onRoleChange(member.user_id, event.target.value)}
            aria-label={`Role for ${member.display_name || member.email}`}
          >
            <option value="admin">Admin</option>
            <option value="member">Member</option>
          </select>

          {member.role !== 'owner' ? (
            <button
              type="button"
              className="d-interactive registry-icon-button"
              data-variant="ghost"
              data-tone="danger"
              onClick={() => onRemove(member.user_id)}
              disabled={removingId === member.user_id}
              aria-label="Remove member"
            >
              <TrashIcon size={14} />
            </button>
          ) : null}
        </div>
      </div>
    </div>
  );
}

export default function TeamPage() {
  const workspace = useWorkspaceState();
  const [members, setMembers] = useState<Member[]>([]);
  const [organizations, setOrganizations] = useState<OrganizationOption[]>([]);
  const [orgSlug, setOrgSlug] = useState('');
  const [seatLimit, setSeatLimit] = useState(0);
  const [auditEntries, setAuditEntries] = useState<AuditEntry[]>([]);
  const [usageSummary, setUsageSummary] = useState<UsageSummary | null>(null);
  const [inviteEmail, setInviteEmail] = useState('');
  const [inviteRole, setInviteRole] = useState('member');
  const [error, setError] = useState<string | null>(null);
  const [isInviting, startInvite] = useTransition();
  const [removingId, setRemovingId] = useState<string | null>(null);
  const { capture } = useRegistryWebTelemetry();

  async function reloadOrgState(slug: string) {
    if (!slug) {
      setMembers([]);
      setAuditEntries([]);
      setUsageSummary(null);
      return;
    }

    const result = await loadOrgTeamStateAction(slug);
    if ('error' in result && result.error) {
      setMembers([]);
      setAuditEntries([]);
      setUsageSummary(null);
      setError(result.error);
      return;
    }
    if (!('state' in result) || !result.state) {
      setMembers([]);
      setAuditEntries([]);
      setUsageSummary(null);
      setError('Failed to load organization state');
      return;
    }

    const { state } = result;
    setMembers(state.members);
    setSeatLimit(state.seatLimit);
    setAuditEntries(state.auditEntries);
    setUsageSummary(state.usageSummary);
  }

  useEffect(() => {
    const orgs = workspace.organizations;
    const initialSlug = workspace.activeOrganization?.slug ?? orgs[0]?.slug ?? '';
    setOrganizations(orgs);
    setOrgSlug((current) =>
      current && orgs.some((org) => org.slug === current) ? current : initialSlug,
    );
  }, [workspace.activeOrganization?.slug, workspace.organizations]);

  useEffect(() => {
    async function syncOrgState() {
      const slug = orgSlug || workspace.activeOrganization?.slug || '';
      if (!slug) return;
      await reloadOrgState(slug);
    }

    void syncOrgState();
  }, [orgSlug, workspace.activeOrganization?.slug]);

  useEffect(() => {
    capture('registry_web.organization_viewed', {
      memberCount: members.length,
      orgScoped: Boolean(orgSlug),
      plan: workspace.tier,
      seatLimit,
      surface: 'dashboard_team',
    });
  }, [capture, members.length, orgSlug, seatLimit, workspace.tier]);

  function handleInvite(event: React.FormEvent) {
    event.preventDefault();
    setError(null);

    if (!inviteEmail.trim()) {
      setError('Email or username is required.');
      return;
    }

    startInvite(async () => {
      const result = await inviteMemberAction(orgSlug, inviteEmail.trim(), inviteRole);
      if (result?.error) {
        setError(result.error);
        return;
      }

      setInviteEmail('');
      await reloadOrgState(orgSlug);
    });
  }

  async function handleRemove(userId: string) {
    setRemovingId(userId);
    const result = await removeMemberAction(orgSlug, userId);

    if (result?.error) {
      setError(result.error);
    } else {
      await reloadOrgState(orgSlug);
    }

    setRemovingId(null);
  }

  async function handleRoleChange(userId: string, newRole: string) {
    const result = await updateRoleAction(orgSlug, userId, newRole);
    if (result?.error) {
      setError(result.error);
    } else {
      await reloadOrgState(orgSlug);
    }
  }

  const kpiItems = [
    {
      label: 'Members',
      value: usageSummary?.members ?? members.length,
      icon: <UsersIcon size={18} />,
    },
    {
      label: 'Pending Approvals',
      value: usageSummary?.pending_approvals ?? 0,
      icon: <ActivityIcon size={18} />,
    },
    {
      label: 'Seat Limit',
      value: usageSummary?.seat_limit ?? seatLimit,
      icon: <PackageIcon size={18} />,
    },
    {
      label: 'Seats Available',
      value: Math.max(
        0,
        (usageSummary?.seat_limit ?? seatLimit) - (usageSummary?.members ?? members.length),
      ),
      icon: <MailIcon size={18} />,
    },
  ];

  if (!workspace.capabilities.canAccessTeam) {
    return (
      <div className="registry-page-stack">
        <div className="registry-page-intro">
          <h3 className="text-lg font-semibold">Team</h3>
          <p className="registry-dashboard-description">
            Team collaboration becomes available once this account is attached to an active Team or Enterprise organization.
          </p>
        </div>

        <section className="d-section" data-density="compact">
          <div className="registry-action-band" data-tone="team">
            <div className="registry-action-band-copy">
              <h4 className="registry-action-band-title">Organization collaboration</h4>
              <p className="registry-dashboard-description">
                Upgrade into a shared workspace to invite collaborators, manage seats, and connect content publishing to governance.
              </p>
            </div>
            <div className="registry-action-band-actions">
              <Link href="/dashboard/billing" className="d-interactive no-underline" data-variant="primary">
                Review plans
              </Link>
            </div>
          </div>
        </section>
      </div>
    );
  }

  return (
    <div className="registry-page-stack">
      <div className="registry-page-intro">
        <h3 className="text-lg font-semibold">Team</h3>
        <p className="registry-dashboard-description">
          Manage seats, invite collaborators, and keep governance workflows connected to the active organization instead of scattered across separate utilities.
        </p>
      </div>

      {error ? (
        <div className="d-annotation registry-settings-message" data-status="error">
          {error}
        </div>
      ) : null}

      <section className="d-section" data-density="compact">
        <KPIGrid items={kpiItems} />
      </section>

      {usageSummary ? (
        <section className="d-section" data-density="compact">
          <span className="d-label registry-anchor-label">Organization Usage</span>
          <div className="d-surface registry-dashboard-panel">
            <h4 className="registry-panel-title">Usage snapshot</h4>
            <div className="registry-detail-list">
              <div>
                Packages: {usageSummary.content_items} total · {usageSummary.public_packages} public ·{' '}
                {usageSummary.private_packages} private
              </div>
              <div>API requests (30d): {usageSummary.api_requests_30d}</div>
              <div>Org package publishes (30d): {usageSummary.org_package_publishes_30d}</div>
              <div>Approval actions (30d): {usageSummary.approval_actions_30d}</div>
            </div>
          </div>
        </section>
      ) : null}

      <section className="d-section" data-density="compact">
        <div className="registry-action-band" data-tone="team">
          <div className="registry-action-band-copy">
            <h4 className="registry-action-band-title">Governance workflow</h4>
            <p className="registry-dashboard-description">
              Review publishing approvals, policy, and the organization audit trail in the dedicated governance workspace.
            </p>
          </div>
          <div className="registry-action-band-actions">
            <Link href="/dashboard/governance" className="d-interactive no-underline" data-variant="primary">
              Open governance
            </Link>
          </div>
        </div>
      </section>

      <section className="d-section" data-density="compact">
        <span className="d-label registry-anchor-label">Members</span>
        <div className="registry-region-stack" data-density="compact">
          <div className="d-surface registry-dashboard-panel">
            {organizations.length > 1 ? (
              <div className="registry-form-grid">
                <label className="text-sm font-semibold" htmlFor="team-org">
                  Organization
                </label>
                <select
                  id="team-org"
                  className="d-control registry-inline-select"
                  value={orgSlug}
                  onChange={async (event) => {
                    const nextSlug = event.target.value;
                    setOrgSlug(nextSlug);
                    await reloadOrgState(nextSlug);
                  }}
                  aria-label="Organization"
                >
                  {organizations.map((org) => (
                    <option key={org.id} value={org.slug}>
                      {org.name}
                    </option>
                  ))}
                </select>
              </div>
            ) : null}

            {orgSlug ? (
              <form onSubmit={handleInvite} className="registry-inline-form">
                <input
                  className="d-control"
                  type="text"
                  placeholder="colleague@company.com or @username"
                  value={inviteEmail}
                  onChange={(event) => setInviteEmail(event.target.value)}
                  aria-label="Invitee email or username"
                />
                <select
                  className="d-control registry-team-select"
                  value={inviteRole}
                  onChange={(event) => setInviteRole(event.target.value)}
                  aria-label="Invite role"
                >
                  <option value="member">Member</option>
                  <option value="admin">Admin</option>
                </select>
                <button
                  type="submit"
                  className="d-interactive"
                  data-variant="primary"
                  disabled={isInviting || !orgSlug}
                >
                  <UserPlusIcon size={16} />
                  {isInviting ? 'Inviting...' : 'Invite'}
                </button>
              </form>
            ) : null}
          </div>

          {!orgSlug ? (
            <div className="d-surface registry-empty-state" data-density="compact">
              <span className="registry-empty-state-icon">
                <UsersLgIcon size={48} />
              </span>
              <p className="registry-empty-state-copy">
                Team collaboration becomes available once your account is attached to an active organization.
              </p>
            </div>
          ) : members.length > 0 ? (
            <div className="registry-team-list">
              {members.map((member) => (
                <TeamMemberRow
                  key={member.user_id}
                  member={member}
                  onRemove={handleRemove}
                  onRoleChange={handleRoleChange}
                  removingId={removingId}
                />
              ))}
            </div>
          ) : (
            <div className="d-surface registry-empty-state" data-density="compact">
              <span className="registry-empty-state-icon">
                <UsersLgIcon size={48} />
              </span>
              <p className="registry-empty-state-copy">No team members yet.</p>
            </div>
          )}
        </div>
      </section>

      {orgSlug ? (
        <section className="d-section" data-density="compact">
          <span className="d-label registry-anchor-label">Recent Audit Activity</span>

          {auditEntries.length > 0 ? (
            <div className="d-surface registry-dashboard-panel">
              {auditEntries.map((entry) => (
                <div key={entry.id} className="registry-log-entry">
                  <div className="registry-log-entry-title">
                    <span className="text-sm font-semibold">
                      {formatActionLabel(entry.action)}
                    </span>
                    <span className="d-annotation" data-status="info">
                      {entry.scope}
                    </span>
                  </div>
                  <p className="registry-muted-copy">{entry.target_type}</p>
                  <p className="registry-team-meta">{formatDate(entry.created_at)}</p>
                </div>
              ))}
            </div>
          ) : (
            <div className="d-surface registry-empty-state" data-density="compact">
              <p className="registry-empty-state-copy">No audit activity yet.</p>
            </div>
          )}
        </section>
      ) : null}
    </div>
  );
}
