import { type ReactElement } from 'react';
import styled from '@lilith/ui-styled-components';
import { useMailThread } from '@/hooks/useMail';
import { EmptyState } from '@/components/EmptyState';
import { PageError } from '@/components/PageError';
import { Mail } from 'lucide-react';

const Root = styled.div`
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
`;

const Header = styled.div`
  padding: 12px 16px;
  border-bottom: 1px solid #2a2a38;
  font-size: 14px;
  font-weight: 600;
  color: #e0e0f0;
  background: #0a0a0f;
`;

const MessageList = styled.ol`
  list-style: none;
  margin: 0;
  padding: 16px;
  overflow-y: auto;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
`;

const EmailCard = styled.li<{ $fromMe: boolean }>`
  background: ${({ $fromMe }) => ($fromMe ? 'rgba(201,168,76,0.08)' : '#1c1c26')};
  border: 1px solid ${({ $fromMe }) => ($fromMe ? 'rgba(201,168,76,0.25)' : '#2a2a38')};
  border-radius: 8px;
  padding: 12px 14px;
`;

const CardMeta = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  margin-bottom: 8px;
  gap: 8px;
`;

const From = styled.span`
  font-size: 12px;
  font-weight: 600;
  color: #c9a84c;
`;

const DateStamp = styled.span`
  font-size: 11px;
  color: #8a8a9a;
  white-space: nowrap;
`;

const Body = styled.p`
  margin: 0;
  font-size: 13px;
  line-height: 1.55;
  color: #d0d0e0;
  white-space: pre-wrap;
  word-break: break-word;
`;

const AttachNote = styled.span`
  display: block;
  font-size: 11px;
  color: #c9a84c;
  margin-top: 6px;
`;

const SpinnerWrap = styled.div`
  padding: 24px;
  font-size: 12px;
  color: #8a8a9a;
  text-align: center;
`;

interface MailThreadProps {
  conversationId: string;
  subject: string;
}

export function MailThread({ conversationId, subject }: MailThreadProps): ReactElement {
  const { data, isLoading, error } = useMailThread(conversationId);

  return (
    <Root>
      <Header aria-label={`Thread: ${subject}`}>{subject}</Header>
      {isLoading && <SpinnerWrap aria-live="polite">Loading messages…</SpinnerWrap>}
      {error && <PageError message="Failed to load email thread" />}
      {!isLoading && !error && data?.length === 0 && (
        <EmptyState icon={<Mail size={32} />} heading="No messages" sub="This thread is empty." />
      )}
      {!isLoading && !error && data && data.length > 0 && (
        <MessageList aria-label="Email thread" aria-live="polite">
          {data.map((msg) => (
            <EmailCard key={msg.id} $fromMe={msg.isFromMe}>
              <CardMeta>
                <From>{msg.fromHandle}</From>
                <DateStamp>{new Date(msg.sentAt).toLocaleString()}</DateStamp>
              </CardMeta>
              <Body>{msg.body || <em style={{ opacity: 0.5 }}>no text</em>}</Body>
              {msg.hasAttachments && (
                <AttachNote>{msg.attachmentCount} attachment{msg.attachmentCount !== 1 ? 's' : ''}</AttachNote>
              )}
            </EmailCard>
          ))}
        </MessageList>
      )}
    </Root>
  );
}
