import { useState, type ReactElement } from 'react';
import styled from '@lilith/ui-styled-components';
import { Search, User, X } from 'lucide-react';
import { useContacts } from '@/hooks/useContacts';
import { EmptyState } from '@/components/EmptyState';
import { PageError } from '@/components/PageError';
import type { Contact } from '@/types';

// ---------------------------------------------------------------------------
// Styles
// ---------------------------------------------------------------------------

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

const PageHeading = styled.h1`
  margin: 0;
  padding: 14px 20px;
  font-size: 18px;
  font-weight: 700;
  color: #e0e0f0;
  border-bottom: 1px solid #2a2a38;
  background: #0a0a0f;
  display: flex;
  align-items: center;
  justify-content: space-between;
`;

const SearchBar = styled.div`
  padding: 12px 16px;
  border-bottom: 1px solid #2a2a38;
  background: #0d0d14;
  display: flex;
  align-items: center;
  gap: 8px;
`;

const SearchInput = styled.input`
  flex: 1;
  background: #13131a;
  border: 1px solid #2a2a38;
  border-radius: 6px;
  color: #e0e0f0;
  font-size: 13px;
  padding: 6px 10px;
  outline: none;

  &::placeholder {
    color: #555566;
  }

  &:focus {
    border-color: rgba(201, 168, 76, 0.4);
  }
`;

const ClearBtn = styled.button`
  background: none;
  border: none;
  color: #8a8a9a;
  cursor: pointer;
  padding: 2px;
  display: flex;
  align-items: center;

  &:hover {
    color: #e0e0f0;
  }
`;

const List = styled.div`
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
`;

const Card = styled.div`
  background: #13131a;
  border: 1px solid #2a2a38;
  border-radius: 8px;
  padding: 16px;
  transition: border-color 0.15s;

  &:hover {
    border-color: rgba(201, 168, 76, 0.3);
  }
`;

const CardHeader = styled.div`
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 10px;
`;

const Avatar = styled.div`
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: rgba(201, 168, 76, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  color: #c9a84c;
`;

const ContactMeta = styled.div`
  flex: 1;
  min-width: 0;
`;

const ContactName = styled.div`
  font-size: 14px;
  font-weight: 600;
  color: #e0e0f0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const ContactHandle = styled.div`
  font-size: 12px;
  color: #8a8a9a;
  margin-top: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const SummarySection = styled.div`
  display: flex;
  flex-direction: column;
  gap: 6px;
`;

const SummaryRow = styled.div<{ $variant: 'recent' | 'overview' | 'recap' }>`
  font-size: 12px;
  line-height: 1.5;
  color: ${({ $variant }) => {
    if ($variant === 'recent') return '#c9a84c';
    if ($variant === 'overview') return '#c0c0d0';
    return '#8a8a9a';
  }};
  padding-left: 8px;
  border-left: 2px solid ${({ $variant }) => {
    if ($variant === 'recent') return '#c9a84c';
    if ($variant === 'overview') return '#3a3a4a';
    return '#2a2a38';
  }};
`;

const NoPendingSummary = styled.div`
  font-size: 12px;
  color: #444455;
  font-style: italic;
`;

const CountBadge = styled.span`
  font-size: 12px;
  font-weight: 400;
  color: #8a8a9a;
  margin-left: 8px;
`;

// ---------------------------------------------------------------------------
// Sub-components
// ---------------------------------------------------------------------------

function ContactCard({ contact }: { contact: Contact }): ReactElement {
  const { summaryData } = contact;
  const name = contact.displayName || contact.handle;

  return (
    <Card>
      <CardHeader>
        <Avatar aria-hidden="true">
          <User size={18} />
        </Avatar>
        <ContactMeta>
          <ContactName title={name}>{name}</ContactName>
          {contact.displayName && contact.handle !== contact.displayName && (
            <ContactHandle>{contact.handle}</ContactHandle>
          )}
          {contact.phoneNumbers.length > 0 && !contact.displayName && (
            <ContactHandle>{contact.phoneNumbers[0]}</ContactHandle>
          )}
        </ContactMeta>
      </CardHeader>

      <SummarySection>
        {summaryData ? (
          <>
            {summaryData.mostRecently && (
              <SummaryRow $variant="recent">{summaryData.mostRecently}</SummaryRow>
            )}
            {summaryData.overallSummary && (
              <SummaryRow $variant="overview">{summaryData.overallSummary}</SummaryRow>
            )}
            {summaryData.recap && (
              <SummaryRow $variant="recap">{summaryData.recap}</SummaryRow>
            )}
            {!summaryData.mostRecently && !summaryData.overallSummary && !summaryData.recap && (
              <NoPendingSummary>No message history available</NoPendingSummary>
            )}
          </>
        ) : (
          <NoPendingSummary>Summary pending…</NoPendingSummary>
        )}
      </SummarySection>
    </Card>
  );
}

// ---------------------------------------------------------------------------
// Main tab
// ---------------------------------------------------------------------------

export function ContactsTab(): ReactElement {
  const [query, setQuery] = useState('');
  const { data: contacts, isLoading, error } = useContacts();

  const filtered = contacts
    ? contacts.filter((c) => {
        if (!query) return true;
        const q = query.toLowerCase();
        return (
          c.displayName.toLowerCase().includes(q) ||
          c.handle.toLowerCase().includes(q) ||
          c.phoneNumbers.some((p) => p.includes(q)) ||
          c.emails.some((e) => e.toLowerCase().includes(q))
        );
      })
    : [];

  return (
    <Root>
      <PageHeading>
        <span>
          Contacts
          {contacts && <CountBadge>{contacts.length.toLocaleString()}</CountBadge>}
        </span>
      </PageHeading>

      <SearchBar>
        <Search size={14} color="#555566" aria-hidden="true" />
        <SearchInput
          type="search"
          placeholder="Filter by name, handle, or phone…"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          aria-label="Filter contacts"
        />
        {query && (
          <ClearBtn onClick={() => setQuery('')} aria-label="Clear filter">
            <X size={14} />
          </ClearBtn>
        )}
      </SearchBar>

      {error && <PageError message={error instanceof Error ? error.message : 'Failed to load contacts'} />}

      {isLoading && (
        <EmptyState
          icon={<User size={32} />}
          heading="Loading contacts…"
        />
      )}

      {!isLoading && !error && contacts && contacts.length === 0 && (
        <EmptyState
          icon={<User size={32} />}
          heading="No contacts"
          sub="Contacts will appear here once synced from your device."
        />
      )}

      {!isLoading && !error && filtered.length === 0 && contacts && contacts.length > 0 && (
        <EmptyState
          icon={<Search size={32} />}
          heading="No matches"
          sub={`No contacts match "${query}"`}
        />
      )}

      {!isLoading && filtered.length > 0 && (
        <List role="list" aria-label="Contact list">
          {filtered.map((contact) => (
            <ContactCard key={contact.id} contact={contact} />
          ))}
        </List>
      )}
    </Root>
  );
}
