import React from 'react';
import styled, { css, useTheme as useStyledTheme } from 'styled-components';
import { HiUserAdd, HiX } from 'react-icons/hi';
import { useLocale } from '@/app/providers/LocaleProvider';
import { CollaboratorPicker } from '@/features/tickets/components/CollaboratorPicker';
import { IconButton, UserAvatar } from '@/shared/components/ui';
import type { TicketCollaborator } from '@/features/tickets/types/collaborator.types';
import type { TicketUserRef } from '@/features/tickets/types/ticket.types';
import {
  getParticipantColor,
  type ParticipantColor,
} from '@/features/tickets/utils/participantColors';
import {
  buildTicketParticipantContext,
  resolveTicketParticipantColor,
} from '@/features/tickets/utils/ticketParticipantContext';
import type { Theme } from '@/styles/theme';

const Shell = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0;
  min-width: 0;
`;

const TeamPanel = styled.div`
  display: flex;
  flex-direction: column;
  border-radius: ${({ theme }) => theme.borderRadius.md};
  border: 1px solid ${({ theme }) => theme.colors.borderSoft};
  background: ${({ theme }) => theme.colors.surfaceInset};
  overflow: hidden;
`;

const CollaboratorsPanel = styled.div`
  display: flex;
  flex-direction: column;
  margin-top: ${({ theme }) => theme.spacing[4]};
  border-radius: ${({ theme }) => theme.borderRadius.md};
  border: 1px solid ${({ theme }) => theme.colors.borderSoft};
  background: ${({ theme }) => theme.colors.surface};
  overflow: hidden;
`;

const SubsectionHeader = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: ${({ theme }) => theme.spacing[2]};
  padding: ${({ theme }) => `${theme.spacing[3]} ${theme.spacing[4]}`};
  border-bottom: 1px solid ${({ theme }) => theme.colors.borderSoft};
  background: ${({ theme }) => theme.colors.surfaceInset};
`;

const SubsectionTitle = styled.h4`
  margin: 0;
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  color: ${({ theme }) => theme.colors.text.secondary};
  text-transform: uppercase;
  letter-spacing: ${({ theme }) => theme.typography.letterSpacing.wider};
  text-align: start;
`;

const CountBadge = styled.span`
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 1.25rem;
  padding: 0 ${({ theme }) => theme.spacing[2]};
  border-radius: ${({ theme }) => theme.borderRadius.full};
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  color: ${({ theme }) => theme.colors.text.secondary};
  background: ${({ theme }) => theme.colors.surface};
  border: 1px solid ${({ theme }) => theme.colors.borderSoft};
`;

const RowList = styled.div`
  display: flex;
  flex-direction: column;
`;

const ParticipantRow = styled.div<{ $interactive?: boolean }>`
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[3]};
  padding: ${({ theme }) => theme.spacing[3]} ${({ theme }) => theme.spacing[4]};
  min-width: 0;

  &:not(:last-child) {
    border-bottom: 1px solid ${({ theme }) => theme.colors.borderSoft};
  }

  ${({ $interactive, theme }) =>
    $interactive &&
    css`
      &:hover {
        background: ${theme.colors.surfaceInset};
      }
    `}
`;

const RowBody = styled.div`
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.spacing[1]};
`;

const RowName = styled.span<{ $color?: string }>`
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  color: ${({ $color, theme }) => $color ?? theme.colors.text.primary};
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: start;
`;

const RowEmail = styled.span`
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  color: ${({ theme }) => theme.colors.text.tertiary};
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: start;
`;

const RoleWrap = styled.div`
  flex-shrink: 0;
`;

const RoleBadge = styled.span<{ $color: string; $background: string; $border: string }>`
  font-size: 0.625rem;
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  color: ${({ $color }) => $color};
  padding: 1px ${({ theme }) => theme.spacing[2]};
  border-radius: ${({ theme }) => theme.borderRadius.sm};
  background: ${({ $background }) => $background};
  border: 1px solid ${({ $border }) => $border};
  white-space: nowrap;
`;

const EmptyState = styled.div`
  padding: ${({ theme }) => theme.spacing[5]} ${({ theme }) => theme.spacing[4]};
  text-align: center;
`;

const EmptyTitle = styled.p`
  margin: 0 0 ${({ theme }) => theme.spacing[1]};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  color: ${({ theme }) => theme.colors.text.primary};
`;

const EmptyHint = styled.p`
  margin: 0;
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  color: ${({ theme }) => theme.colors.text.secondary};
  line-height: ${({ theme }) => theme.typography.lineHeight.relaxed};
`;

const AddDock = styled.div`
  margin-top: ${({ theme }) => theme.spacing[4]};
  padding-top: ${({ theme }) => theme.spacing[4]};
  border-top: 1px solid ${({ theme }) => theme.colors.borderSoft};
`;

const AddLabel = styled.div`
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[2]};
  margin-bottom: ${({ theme }) => theme.spacing[3]};
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  color: ${({ theme }) => theme.colors.text.secondary};
  text-transform: uppercase;
  letter-spacing: ${({ theme }) => theme.typography.letterSpacing.wider};

  svg {
    width: 14px;
    height: 14px;
    color: ${({ theme }) => theme.colors.primary};
  }
`;

interface ParticipantRowItemProps {
  name: string;
  email?: string;
  roleLabel: string;
  participantColor: ParticipantColor;
  avatarSrc?: string | null;
  onRemove?: () => void;
  removing?: boolean;
}

const ParticipantRowItem: React.FC<ParticipantRowItemProps & { removeLabel: string }> = ({
  name,
  email,
  roleLabel,
  participantColor,
  avatarSrc,
  onRemove,
  removing = false,
  removeLabel,
}) => (
  <ParticipantRow $interactive={Boolean(onRemove)}>
    <UserAvatar
      name={name}
      src={avatarSrc}
      size="md"
      ringColor={participantColor.avatarBackground}
      avatarBackground={participantColor.avatarBackground}
      avatarText={participantColor.avatarText}
    />
    <RowBody>
      <RowName $color={participantColor.text}>{name}</RowName>
      {email ? <RowEmail>{email}</RowEmail> : null}
    </RowBody>
    <RoleWrap>
      <RoleBadge
        $color={participantColor.text}
        $background={participantColor.background}
        $border={participantColor.border}
      >
        {roleLabel}
      </RoleBadge>
    </RoleWrap>
    {onRemove ? (
      <IconButton
        type="button"
        size="sm"
        tone="danger"
        label={removeLabel}
        disabled={removing}
        onClick={onRemove}
        aria-busy={removing}
      >
        <HiX aria-hidden />
      </IconButton>
    ) : null}
  </ParticipantRow>
);

interface CollaboratorsSectionProps {
  collaborators: TicketCollaborator[];
  assignee?: TicketUserRef | null;
  requester: TicketUserRef;
  departmentId: string;
  ticketId: string;
  canManage: boolean;
  onAdd: (userId: string) => Promise<void>;
  onRemove: (userId: string) => Promise<void>;
  isAdding?: boolean;
  removingUserId?: string | null;
}

export const CollaboratorsSection: React.FC<CollaboratorsSectionProps> = ({
  collaborators,
  assignee,
  requester,
  departmentId,
  ticketId,
  canManage,
  onAdd,
  onRemove,
  isAdding = false,
  removingUserId = null,
}) => {
  const { t } = useLocale();
  const { mode } = useStyledTheme() as Theme;
  const participantContext = buildTicketParticipantContext({ requester, assignee, collaborators });
  const requesterColor = resolveTicketParticipantColor(
    requester.id,
    participantContext,
    mode,
  );

  const excludeIds = [
    requester.id,
    ...(assignee ? [assignee.id] : []),
    ...collaborators.map((collaborator) => collaborator.user_id),
  ];

  return (
    <Shell data-tour="ticket-collaborators">
      <TeamPanel>
        <SubsectionHeader>
          <SubsectionTitle>{t('tickets:collaborators.teamTitle')}</SubsectionTitle>
        </SubsectionHeader>
        <RowList>
          <ParticipantRowItem
            name={requester.name}
            email={requester.email}
            roleLabel={t('tickets:fields.requester')}
            participantColor={requesterColor}
            removeLabel={t('tickets:collaborators.remove')}
          />
          <ParticipantRowItem
            name={assignee?.name ?? t('tickets:unassigned')}
            email={assignee?.email}
            roleLabel={t('tickets:fields.assignee')}
            participantColor={
              assignee
                ? resolveTicketParticipantColor(assignee.id, participantContext, mode)
                : getParticipantColor('', undefined, mode)
            }
            removeLabel={t('tickets:collaborators.remove')}
          />
        </RowList>
      </TeamPanel>

      <CollaboratorsPanel>
        <SubsectionHeader>
          <SubsectionTitle>{t('tickets:sections.collaborators')}</SubsectionTitle>
          <CountBadge>{collaborators.length}</CountBadge>
        </SubsectionHeader>

        {collaborators.length === 0 ? (
          <EmptyState>
            <EmptyTitle>{t('tickets:collaborators.emptyTitle')}</EmptyTitle>
            <EmptyHint>{t('tickets:collaborators.emptyHint')}</EmptyHint>
          </EmptyState>
        ) : (
          <RowList>
            {collaborators.map((collaborator) => (
              <ParticipantRowItem
                key={collaborator.id}
                name={collaborator.name}
                email={collaborator.email}
                roleLabel={t('tickets:collaborators.roleLabel')}
                participantColor={resolveTicketParticipantColor(
                  collaborator.user_id,
                  participantContext,
                  mode,
                )}
                avatarSrc={collaborator.avatar}
                removeLabel={t('tickets:collaborators.remove')}
                onRemove={
                  canManage ? () => void onRemove(collaborator.user_id) : undefined
                }
                removing={removingUserId === collaborator.user_id}
              />
            ))}
          </RowList>
        )}
      </CollaboratorsPanel>

      {canManage && (
        <AddDock>
          <AddLabel>
            <HiUserAdd aria-hidden />
            {t('tickets:collaborators.addLabel')}
          </AddLabel>
          <CollaboratorPicker
            embedded
            departmentId={departmentId}
            ticketId={ticketId}
            excludeUserIds={excludeIds}
            disabled={isAdding}
            onSelect={(user) => void onAdd(user.id)}
          />
        </AddDock>
      )}
    </Shell>
  );
};
