import React, { ReactNode } from 'react';
import styled from 'styled-components';
import { useLocale } from '@/app/providers/LocaleProvider';
import { Button, Spinner } from '@/shared/components/ui';
import { RepliesThread } from '@/features/tickets/components/RepliesThread';
import {
  ConversationComposer,
  type ConversationComposerProps,
} from '@/features/tickets/components/ConversationComposer';
import type { TicketReply } from '@/features/tickets/types/ticket.types';
import type { TicketParticipantContext } from '@/features/tickets/utils/ticketParticipantContext';

const Shell = styled.section`
  background-color: ${({ theme }) => theme.colors.surface};
  border: 1px solid ${({ theme }) => theme.colors.borderSoft};
  border-radius: ${({ theme }) => theme.borderRadius.lg};
  box-shadow: ${({ theme }) => theme.shadows.sm};
  overflow: hidden;
`;

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

const ShellTitle = styled.h2`
  margin: 0;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  color: ${({ theme }) => theme.colors.text.primary};
  text-align: start;
`;

const MessageCount = styled.span`
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 1.5rem;
  padding: ${({ theme }) => `${theme.spacing[1]} ${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.surfaceInset};
  border: 1px solid ${({ theme }) => theme.colors.borderSoft};
`;

const ThreadCanvas = styled.div`
  padding: ${({ theme }) => theme.layout.cardPaddingMd};
  background: ${({ theme }) => theme.colors.surfaceInset};
  min-height: 12rem;

  @media (max-width: 768px) {
    padding: ${({ theme }) => theme.layout.cardPaddingSm};
  }
`;

const ComposerDock = styled.div`
  padding: ${({ theme }) => theme.layout.cardPaddingMd};
  border-top: 1px solid ${({ theme }) => theme.colors.borderSoft};
  background: ${({ theme }) => theme.colors.surface};

  @media (max-width: 768px) {
    padding: ${({ theme }) => theme.layout.cardPaddingSm};
  }
`;

const ThreadState = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: ${({ theme }) => theme.spacing[3]};
  padding: ${({ theme }) => theme.spacing[10]} ${({ theme }) => theme.spacing[4]};
  text-align: center;
  color: ${({ theme }) => theme.colors.text.secondary};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
`;

export interface ConversationSectionProps {
  replies: TicketReply[];
  participantContext: TicketParticipantContext;
  composer: ConversationComposerProps;
  threadLoading?: boolean;
  threadError?: boolean;
  onRetryThread?: () => void;
}

function renderThreadBody(props: {
  loading?: boolean;
  error?: boolean;
  onRetry?: () => void;
  loadingLabel: string;
  errorLabel: string;
  retryLabel: string;
  children: ReactNode;
}): ReactNode {
  if (props.loading) {
    return (
      <ThreadState role="status">
        <Spinner />
        <p>{props.loadingLabel}</p>
      </ThreadState>
    );
  }

  if (props.error) {
    return (
      <ThreadState role="alert">
        <p>{props.errorLabel}</p>
        {props.onRetry ? (
          <Button variant="outline" size="sm" onClick={props.onRetry}>
            {props.retryLabel}
          </Button>
        ) : null}
      </ThreadState>
    );
  }

  return props.children;
}

export const ConversationSection: React.FC<ConversationSectionProps> = ({
  replies,
  participantContext,
  composer,
  threadLoading = false,
  threadError = false,
  onRetryThread,
}) => {
  const { t } = useLocale();

  return (
    <Shell data-tour="ticket-conversation" aria-label={t('tickets:sections.conversation')}>
      <ShellHeader>
        <ShellTitle>{t('tickets:sections.conversation')}</ShellTitle>
        <MessageCount title={t('tickets:sections.conversation')}>{replies.length}</MessageCount>
      </ShellHeader>

      <ThreadCanvas>
        {renderThreadBody({
          loading: threadLoading,
          error: threadError,
          onRetry: onRetryThread,
          loadingLabel: t('tickets:states.loading'),
          errorLabel: t('tickets:states.errorReplies'),
          retryLabel: t('tickets:states.retry'),
          children: (
            <RepliesThread
              replies={replies}
              participantContext={participantContext}
            />
          ),
        })}
      </ThreadCanvas>

      <ComposerDock>
        <ConversationComposer {...composer} embedded />
      </ComposerDock>
    </Shell>
  );
};
