import { useState } from 'react';
import styled from '@lilith/ui-styled-components';
import { Phone, Clock, User } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import { fetchCalls, fetchCallStats, type Call, type CallFilter } from '@/api/calls';
import { EmptyState } from '@/components/EmptyState';
import { PageError } from '@/components/PageError';

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;
  gap: 12px;
`;

const Stats = styled.span`
  font-size: 11px;
  color: #8a8a9a;
  font-weight: 500;
`;

const Body = styled.div`
  display: flex;
  flex: 1;
  overflow: hidden;
  flex-direction: column;
`;

const Toolbar = styled.div`
  display: flex;
  gap: 8px;
  padding: 10px 12px;
  border-bottom: 1px solid #1e1e2a;
  background: #0d0d14;
`;

const FilterButton = styled.button<{ $active?: boolean }>`
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 4px 10px;
  font-size: 11px;
  font-weight: 600;
  color: ${(p) => (p.$active ? '#0a0a0f' : '#c9a84c')};
  background: ${(p) => (p.$active ? '#c9a84c' : 'transparent')};
  border: 1px solid #c9a84c;
  border-radius: 4px;
  cursor: pointer;
  &:hover {
    background: ${(p) => (p.$active ? '#b38f3a' : '#1a1a24')};
  }
`;

const TableWrap = styled.div`
  flex: 1;
  overflow: auto;
  padding: 8px 12px;
`;

const Table = styled.table`
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
`;

const Th = styled.th`
  text-align: left;
  padding: 6px 8px;
  color: #8a8a9a;
  font-weight: 500;
  border-bottom: 1px solid #2a2a38;
  position: sticky;
  top: 0;
  background: #0a0a0f;
`;

const Td = styled.td`
  padding: 6px 8px;
  border-bottom: 1px solid #1e1e2a;
  color: #d0d0e0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const Dir = styled.span<{ $dir?: string | null }>`
  padding: 1px 6px;
  border-radius: 3px;
  font-size: 10px;
  font-weight: 600;
  color: #0a0a0f;
  background: ${(p) => (p.$dir === 'outgoing' ? '#6aa84f' : '#5b8def')};
`;

const TypeBadge = styled.span`
  padding: 1px 6px;
  border-radius: 3px;
  font-size: 10px;
  background: #2a2a38;
  color: #a0a0b0;
`;

export function CallsTab() {
  const [filter, setFilter] = useState<CallFilter>({ limit: 100 });

  const { data: stats } = useQuery({
    queryKey: ['calls-stats', filter.deviceId],
    queryFn: () => fetchCallStats(filter.deviceId),
  });

  const { data: calls = [], isLoading, error } = useQuery({
    queryKey: ['calls', filter],
    queryFn: () => fetchCalls(filter),
  });

  const setDirFilter = (dir?: string) => {
    setFilter((f) => ({ ...f, direction: dir, offset: 0 } as CallFilter));
  };
  const setTypeFilter = (t?: string) => {
    setFilter((f) => ({ ...f, callType: t, offset: 0 } as CallFilter));
  };

  const fmtDuration = (s: number | null | undefined) => {
    if (s == null || s <= 0) return '—';
    const m = Math.floor(s / 60);
    const sec = Math.floor(s % 60);
    return m > 0 ? `${m}m ${sec}s` : `${sec}s`;
  };

  const fmtWhen = (iso: string | null | undefined) => {
    if (!iso) return '—';
    try {
      return new Date(iso).toLocaleString();
    } catch {
      return iso;
    }
  };

  return (
    <Root>
      <PageHeading>
        Calls
        <Stats>
          {stats ? `${stats.totalCalls} total` : '—'} {stats?.lastSyncAt ? `· last ${new Date(stats.lastSyncAt).toLocaleDateString()}` : ''}
        </Stats>
      </PageHeading>

      <Toolbar>
        <FilterButton $active={!filter.direction} onClick={() => setDirFilter(undefined)}>
          All
        </FilterButton>
        <FilterButton $active={filter.direction === 'incoming'} onClick={() => setDirFilter('incoming')}>
          Incoming
        </FilterButton>
        <FilterButton $active={filter.direction === 'outgoing'} onClick={() => setDirFilter('outgoing')}>
          Outgoing
        </FilterButton>
        <span style={{ width: 12 }} />
        <FilterButton $active={!filter.callType} onClick={() => setTypeFilter(undefined)}>
          All types
        </FilterButton>
        <FilterButton $active={filter.callType === 'telephony'} onClick={() => setTypeFilter('telephony')}>
          Phone
        </FilterButton>
        <FilterButton $active={filter.callType === 'facetime_video'} onClick={() => setTypeFilter('facetime_video')}>
          FaceTime
        </FilterButton>
        <FilterButton $active={filter.callType === 'facetime_audio'} onClick={() => setTypeFilter('facetime_audio')}>
          FaceTime Audio
        </FilterButton>
      </Toolbar>

      <Body>
        {error ? (
          <PageError message={error instanceof Error ? error.message : 'Failed to load calls'} />
        ) : isLoading ? (
          <EmptyState icon={<Phone size={32} />} heading="Loading calls…" />
        ) : calls.length === 0 ? (
          <EmptyState icon={<Phone size={32} />} heading="No calls" sub="History will appear after the next iCalls sync on the Mac." />
        ) : (
          <TableWrap>
            <Table>
              <thead>
                <tr>
                  <Th>When</Th>
                  <Th>Direction</Th>
                  <Th>Type</Th>
                  <Th>Contact / Address</Th>
                  <Th>Duration</Th>
                  <Th>Answered</Th>
                </tr>
              </thead>
              <tbody>
                {calls.map((c: Call) => (
                  <tr key={c.id}>
                    <Td>{fmtWhen(c.startedAt)}</Td>
                    <Td>
                      <Dir $dir={c.direction}>{c.direction ?? '—'}</Dir>
                    </Td>
                    <Td>
                      <TypeBadge>{c.callType?.replace('facetime_', 'FT ') ?? '—'}</TypeBadge>
                    </Td>
                    <Td title={c.address ?? undefined}>
                      {c.contactName || c.address || 'Unknown'}
                      {c.normalizedAddress && c.normalizedAddress !== c.address ? ` (${c.normalizedAddress})` : ''}
                    </Td>
                    <Td>{fmtDuration(c.durationSeconds)}</Td>
                    <Td>{c.answered ? 'yes' : c.answered === false ? 'no' : '—'}</Td>
                  </tr>
                ))}
              </tbody>
            </Table>
          </TableWrap>
        )}
      </Body>
    </Root>
  );
}
