import React from 'react';
import styled, { useTheme as useStyledTheme } from 'styled-components';
import { HiLockClosed, HiShieldCheck } from 'react-icons/hi';
import { useLocale } from '@/app/providers/LocaleProvider';
import { Card, StatusBadge, UserAvatar } from '@/shared/components/ui';
import type { TicketNote } from '@/features/tickets/types/ticket.types';
import { formatDateTime } from '@/features/tickets/utils/ticketDisplay';
import {
  mixParticipantAccent,
  type ParticipantColor,
} from '@/features/tickets/utils/participantColors';
import {
  resolveTicketParticipantColor,
  type TicketParticipantContext,
} from '@/features/tickets/utils/ticketParticipantContext';
import type { Theme } from '@/styles/theme';

const Thread = styled.div`
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.spacing[4]};
  padding: 0;
`;

const NoteRow = styled.article<{
  $accent: ParticipantColor;
  $surface: string;
  $borderSoft: string;
}>`
  display: flex;
  gap: ${({ theme }) => theme.spacing[3]};
  padding: ${({ theme }) => theme.spacing[4]} ${({ theme }) => theme.spacing[5]};
  border-radius: ${({ theme }) => theme.borderRadius.xl};
  background: ${({ $surface }) => $surface};
  border: 1px solid
    ${({ $accent, $borderSoft }) => mixParticipantAccent($accent.avatarBackground, 20, $borderSoft)};
  border-inline-start: 3px solid ${({ $accent }) => $accent.avatarBackground};
  box-shadow: ${({ theme }) => theme.shadows.sm};
  position: relative;
  overflow: hidden;
`;

const LockBadge = styled.span<{ $accent: ParticipantColor; $borderSoft: string }>`
  position: absolute;
  top: ${({ theme }) => theme.spacing[4]};
  inset-inline-end: ${({ theme }) => theme.spacing[4]};
  width: 32px;
  height: 32px;
  border-radius: ${({ theme }) => theme.borderRadius.full};
  background: ${({ $accent }) => $accent.background};
  border: 1px solid
    ${({ $accent, $borderSoft }) => mixParticipantAccent($accent.avatarBackground, 20, $borderSoft)};
  color: ${({ $accent }) => $accent.text};
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-shadow: ${({ theme }) => theme.shadows.xs};

  svg {
    width: 16px;
    height: 16px;
  }
`;

const NoteBody = styled.div`
  flex: 1;
  min-width: 0;
  padding-inline-end: ${({ theme }) => theme.spacing[8]};
`;

const NoteHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: ${({ theme }) => theme.spacing[4]};
  margin-bottom: ${({ theme }) => theme.spacing[3]};
  flex-wrap: wrap;
`;

const Author = styled.span<{ $color?: string }>`
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ $color, theme }) => $color ?? theme.colors.text.primary};
`;

const RoleLabel = styled.span<{ $color: string; $background: string; $border: string }>`
  display: inline-flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[2]};
  margin-top: 4px;
  font-size: 0.6875rem;
  color: ${({ $color }) => $color};
  background: ${({ $background }) => $background};
  border: 1px solid ${({ $border }) => $border};
  border-radius: ${({ theme }) => theme.borderRadius.full};
  padding: 2px ${({ theme }) => theme.spacing[2]};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  line-height: 1.2;

  svg {
    width: 14px;
    height: 14px;
  }
`;

const Timestamp = styled.time`
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  color: ${({ theme }) => theme.colors.text.tertiary};
`;

const NoteContent = styled.p`
  margin: 0;
  white-space: pre-wrap;
  text-align: start;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  line-height: 1.55;
  color: ${({ theme }) => theme.colors.text.primary};
`;

const EmptyWrap = styled.div`
  padding: ${({ theme }) => theme.spacing[12]} ${({ theme }) => theme.spacing[6]};
  text-align: center;
`;

const EmptyText = styled.p`
  margin: 0;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.secondary};
`;

const SectionHint = styled.p`
  margin: 0 0 ${({ theme }) => theme.spacing[5]};
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  color: ${({ theme }) => theme.colors.text.tertiary};
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[2]};

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

interface NotesSectionProps {
  notes: TicketNote[];
  participantContext: TicketParticipantContext;
}

export const NotesSection: React.FC<NotesSectionProps> = ({ notes, participantContext }) => {
  const { t, locale } = useLocale();
  const { mode, colors } = useStyledTheme() as Theme;

  return (
    <Card variant="muted" padding="md" header={t('tickets:notes')}>
      <SectionHint>
        <HiShieldCheck aria-hidden />
        {t('tickets:detail.internalNote')}
      </SectionHint>
      {notes.length === 0 ? (
        <EmptyWrap>
          <EmptyText>{t('tickets:states.noNotes')}</EmptyText>
        </EmptyWrap>
      ) : (
        <Thread>
          {notes.map((note) => {
            const participantColor = resolveTicketParticipantColor(
              note.user.id,
              participantContext,
              mode,
            );
            return (
            <NoteRow
              key={note.id}
              $accent={participantColor}
              $surface={colors.surfaceElevated}
              $borderSoft={colors.borderSoft}
            >
              <LockBadge
                aria-hidden
                $accent={participantColor}
                $borderSoft={colors.borderSoft}
              >
                <HiLockClosed />
              </LockBadge>
              <UserAvatar
                name={note.user.name}
                size="md"
                ringColor={participantColor.avatarBackground}
                avatarBackground={participantColor.avatarBackground}
                avatarText={participantColor.avatarText}
              />
              <NoteBody>
                <NoteHeader>
                  <div>
                    <Author $color={participantColor.text}>{note.user.name}</Author>
                    <RoleLabel
                      $color={participantColor.text}
                      $background={participantColor.background}
                      $border={participantColor.border}
                    >
                      <HiLockClosed aria-hidden />
                      {t('tickets:detail.internalNote')}
                    </RoleLabel>
                  </div>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                    {note.is_pinned && (
                      <StatusBadge tone="warning" size="sm">
                        {t('tickets:labels.pinned')}
                      </StatusBadge>
                    )}
                    <Timestamp dateTime={note.created_at}>
                      {formatDateTime(note.created_at, locale)}
                    </Timestamp>
                  </div>
                </NoteHeader>
                <NoteContent>{note.content}</NoteContent>
              </NoteBody>
            </NoteRow>
            );
          })}
        </Thread>
      )}
    </Card>
  );
};
