import { useState, type ReactElement } from 'react';
import styled from '@lilith/ui-styled-components';
import {
  useSyncStats,
  useSyncHistory,
  useSyncHealth,
  useSendQueueSummary,
  useSyncThroughput,
  useDiagnostics,
  useFailedSends,
  useRetrySend,
  useActivity,
} from '@/hooks/useSync';
import { EmptyState } from '@/components/EmptyState';
import { PageError } from '@/components/PageError';
import type { SyncSourceStatus } from '@/api/sync';
import type { Diagnostics, ActivityEntry } from '@/api/diagnostics';

// ── Layout ──────────────────────────────────────────────────────────────────

const Root = styled.div`
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;
  overflow-y: auto;
`;

const Card = styled.div`
  background: #13131a;
  border: 1px solid #2a2a38;
  border-radius: 8px;
  padding: 20px;
`;

const CardTitle = styled.h3`
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #e0e0f0;
`;

// ── Native Subsystems ────────────────────────────────────────────────────────

const SubsystemsHeader = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
`;

const CollapseToggle = styled.span`
  font-size: 12px;
  color: #8a8a9a;
`;

const SubsystemsList = styled.div`
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 12px;
`;

const SubsystemRow = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px;
  background: #1e1e2a;
  border-radius: 6px;
  border: 1px solid #2a2a38;
`;

const SubsystemIcon = styled.span`
  font-size: 16px;
  width: 20px;
  text-align: center;
`;

const SubsystemName = styled.span`
  font-size: 13px;
  color: #c0c0d0;
  flex: 1;
  font-weight: 500;
`;

const SubsystemStatus = styled.span<{ $ok: boolean }>`
  font-size: 12px;
  color: ${(p) => (p.$ok ? '#5ae05a' : '#e05a5a')};
`;

const SubsystemAction = styled.a`
  font-size: 11px;
  color: #8a8a9a;
  text-decoration: underline;
  cursor: pointer;
`;

// ── Domain KPI Tiles ─────────────────────────────────────────────────────────

const statusColor: Record<SyncSourceStatus, string> = {
  healthy: '#5ae05a',
  stale: '#e0c85a',
  failing: '#e05a5a',
};

const DomainGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 12px;
`;

const DomainTile = styled.div`
  background: #13131a;
  border: 1px solid #2a2a38;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
`;

const DomainTileHeader = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
`;

const DomainIcon = styled.span`
  font-size: 16px;
  line-height: 1;
`;

const DomainName = styled.span`
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  color: #8a8a9a;
`;

const DomainTotal = styled.span<{ $zero: boolean }>`
  font-size: 28px;
  font-weight: 700;
  line-height: 1;
  color: ${(p) => (p.$zero ? '#4a4a5a' : '#e0e0f0')};
`;

const DomainDelta = styled.span<{ $nonzero: boolean }>`
  font-size: 12px;
  font-weight: 600;
  color: ${(p) => (p.$nonzero ? '#5ae05a' : '#3a3a4a')};
`;

const DomainHealthRow = styled.div`
  display: flex;
  align-items: center;
  gap: 6px;
`;

const DomainHealthDot = styled.span<{ $status: SyncSourceStatus | undefined }>`
  width: 7px;
  height: 7px;
  border-radius: 50%;
  flex-shrink: 0;
  background: ${(p) => (p.$status ? statusColor[p.$status] : '#4a4a5a')};
`;

const DomainHealthText = styled.span<{ $status: SyncSourceStatus | undefined }>`
  font-size: 11px;
  color: ${(p) => (p.$status ? statusColor[p.$status] : '#4a4a5a')};
`;

const OutboundBar = styled.div`
  border-top: 1px solid #2a2a38;
  padding-top: 10px;
  margin-top: 2px;
  display: flex;
  gap: 8px;
`;

const OutboundStat = styled.div`
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 3px;
`;

const OutboundVal = styled.span<{ $alert?: boolean; $positive?: boolean }>`
  font-size: 15px;
  font-weight: 700;
  line-height: 1;
  color: ${(p) => (p.$alert ? '#e05a5a' : p.$positive ? '#5ae05a' : '#c9a84c')};
`;

const OutboundKey = styled.span`
  font-size: 10px;
  text-transform: uppercase;
  letter-spacing: 0.4px;
  color: #6a6a7a;
`;

const StallNote = styled.p`
  margin: 4px 0 0;
  font-size: 11px;
  color: #e05a5a;
`;

// ── Failed Sends ─────────────────────────────────────────────────────────────

const FailedList = styled.div`
  margin-top: 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
`;

const FailedItem = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  background: #1e1e2a;
  border-radius: 6px;
  border: 1px solid #3a1b1b;
`;

const FailedTo = styled.span`
  font-size: 12px;
  color: #c0c0d0;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
`;

const FailedReason = styled.span`
  font-size: 11px;
  color: #e05a5a;
`;

const RetryButton = styled.button<{ $loading: boolean }>`
  padding: 4px 10px;
  font-size: 11px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #e05a5a44;
  background: #4d1b1b;
  color: #e05a5a;
  opacity: ${(p) => (p.$loading ? 0.5 : 1)};

  &:hover:not(:disabled) {
    background: #5a1b1b;
  }

  &:disabled {
    cursor: not-allowed;
  }
`;

// ── History Table ────────────────────────────────────────────────────────────

const HistoryControls = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
`;

const FilterToggle = styled.button<{ $active: boolean }>`
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  border: 1px solid ${(p) => (p.$active ? '#e05a5a88' : '#2a2a38')};
  background: ${(p) => (p.$active ? '#4d1b1b' : '#1e1e2a')};
  color: ${(p) => (p.$active ? '#e05a5a' : '#8a8a9a')};
  transition: all 0.15s;
`;

const HistoryTable = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0;
  border: 1px solid #2a2a38;
  border-radius: 6px;
  overflow: hidden;
`;

const HistoryHeader = styled.div`
  display: grid;
  grid-template-columns: 80px 200px 100px 80px 80px 80px 1fr;
  gap: 12px;
  padding: 12px;
  background: #1c1c26;
  border-bottom: 1px solid #2a2a38;
  font-weight: 600;
  font-size: 12px;
  color: #8a8a9a;
  text-transform: uppercase;
  letter-spacing: 0.5px;
`;

const HistoryRow = styled.div`
  display: grid;
  grid-template-columns: 80px 200px 100px 80px 80px 80px 1fr;
  gap: 12px;
  padding: 12px;
  border-bottom: 1px solid #2a2a38;
  font-size: 13px;
  color: #c0c0d0;
  align-items: center;

  &:last-child {
    border-bottom: none;
  }
`;

const Badge = styled.span<{ $status: string }>`
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  background-color: ${(p) =>
    p.$status === 'success' ? '#1b4d2b' : p.$status === 'error' ? '#4d1b1b' : '#4d4d1b'};
  color: ${(p) =>
    p.$status === 'success' ? '#5ae05a' : p.$status === 'error' ? '#e05a5a' : '#e0e05a'};
`;

const CumulativeFooter = styled.div`
  display: flex;
  gap: 20px;
  padding: 12px 0 0;
  border-top: 1px solid #2a2a38;
  margin-top: 8px;
  flex-wrap: wrap;
`;

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

  strong {
    color: #c0c0d0;
    font-weight: 600;
  }
`;

const ActivityFeed = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0;
  max-height: 260px;
  overflow-y: auto;
  border: 1px solid #2a2a38;
  border-radius: 6px;
`;

const ActivityRow = styled.div<{ $level: string }>`
  display: grid;
  grid-template-columns: 56px 1fr;
  gap: 10px;
  padding: 7px 12px;
  border-bottom: 1px solid #1e1e2a;
  font-size: 12px;
  align-items: baseline;

  &:last-child { border-bottom: none; }

  background: ${(p) =>
    p.$level === 'error' ? 'rgba(77,27,27,0.25)' :
    p.$level === 'success' ? 'rgba(27,77,43,0.18)' :
    'transparent'};
`;

const ActivityLevel = styled.span<{ $level: string }>`
  font-size: 10px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.4px;
  color: ${(p) =>
    p.$level === 'error' ? '#e05a5a' :
    p.$level === 'success' ? '#5ae05a' :
    p.$level === 'warning' ? '#e0e05a' :
    '#8a8a9a'};
`;

const ActivityMsg = styled.span`
  color: #c0c0d0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

// ── Utilities ────────────────────────────────────────────────────────────────

function formatDate(dateStr: string | null): string {
  if (!dateStr) return '—';
  return new Date(dateStr).toLocaleString();
}

function formatDuration(started: string, completed: string | null): string {
  if (!completed) return 'In progress';
  const ms = new Date(completed).getTime() - new Date(started).getTime();
  const s = Math.floor(ms / 1000);
  if (s < 60) return `${s}s`;
  return `${Math.floor(s / 60)}m ${s % 60}s`;
}

function relativeTime(dateStr: string | null): string {
  if (!dateStr) return 'never';
  const diffMs = Date.now() - new Date(dateStr).getTime();
  const s = Math.floor(diffMs / 1000);
  if (s < 60) return `${s}s ago`;
  const m = Math.floor(s / 60);
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

function oldestQueuedAge(dateStr: string | null): number {
  if (!dateStr) return 0;
  return (Date.now() - new Date(dateStr).getTime()) / 1000 / 60;
}

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

function NativeSubsystemsCard({ data }: { data: Diagnostics }): ReactElement {
  const [isExpanded, setIsExpanded] = useState(false);

  interface Subsystem {
    name: string;
    icon: string;
    ok: boolean;
    statusText: string;
    deeplink: string;
  }

  const subsystems: Subsystem[] = [
    {
      name: 'Full Disk Access',
      icon: '💾',
      ok: data.fullDiskAccess,
      statusText: data.fullDiskAccess ? 'OK' : 'Denied',
      deeplink: 'x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles',
    },
    {
      name: 'iMessage DB',
      icon: '💬',
      ok: data.iMessageDb.available,
      statusText: data.iMessageDb.available ? 'OK' : data.iMessageDb.error ?? 'Unavailable',
      deeplink: 'x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles',
    },
    {
      name: 'Mail Scripting',
      icon: '✉️',
      ok: data.mailScriptingBridge.available,
      statusText: data.mailScriptingBridge.available ? 'OK' : data.mailScriptingBridge.error ?? 'Unavailable',
      deeplink: 'x-apple.systempreferences:com.apple.preference.security?Privacy_Automation',
    },
    {
      name: 'Calendar',
      icon: '📅',
      ok: data.calendarAuth === 'authorized',
      statusText: data.calendarAuth === 'authorized' ? 'OK' : data.calendarAuth,
      deeplink: 'x-apple.systempreferences:com.apple.preference.security?Privacy_Calendars',
    },
    {
      name: 'Photos',
      icon: '🖼️',
      ok: data.photosAuth === 'authorized' || data.photosAuth === 'limited',
      statusText: data.photosAuth === 'authorized' || data.photosAuth === 'limited' ? 'OK' : data.photosAuth,
      deeplink: 'x-apple.systempreferences:com.apple.preference.security?Privacy_Photos',
    },
    {
      name: 'Contacts',
      icon: '👤',
      ok: data.contactsAuth === 'authorized',
      statusText: data.contactsAuth === 'authorized' ? 'OK' : data.contactsAuth,
      deeplink: 'x-apple.systempreferences:com.apple.preference.security?Privacy_Contacts',
    },
  ];

  return (
    <Card>
      <SubsystemsHeader onClick={() => setIsExpanded((v) => !v)}>
        <CardTitle style={{ margin: 0 }}>Native Subsystems</CardTitle>
        <CollapseToggle>{isExpanded ? '▲' : '▼'}</CollapseToggle>
      </SubsystemsHeader>
      {isExpanded && (
        <SubsystemsList>
          {subsystems.map((subsystem) => (
            <SubsystemRow key={subsystem.name}>
              <SubsystemIcon>{subsystem.icon}</SubsystemIcon>
              <SubsystemName>{subsystem.name}</SubsystemName>
              <SubsystemStatus $ok={subsystem.ok}>{subsystem.statusText}</SubsystemStatus>
              {!subsystem.ok && (
                <SubsystemAction href={subsystem.deeplink} target="_blank" rel="noopener noreferrer">
                  Open Settings
                </SubsystemAction>
              )}
            </SubsystemRow>
          ))}
        </SubsystemsList>
      )}
    </Card>
  );
}

// ── Main Component ───────────────────────────────────────────────────────────

export function DashboardTab(): ReactElement {
  const [errorsOnly, setErrorsOnly] = useState(true);

  const health = useSyncHealth();
  const queue = useSendQueueSummary();
  const throughput = useSyncThroughput('24h');
  const stats = useSyncStats();
  const history = useSyncHistory(50);
  const diagnostics = useDiagnostics();
  const failedSends = useFailedSends();
  const retrySendMutation = useRetrySend();
  const activity = useActivity();

  const firstError =
    health.error ?? queue.error ?? throughput.error ?? stats.error ?? history.error;

  if (firstError) {
    const message = firstError instanceof Error ? firstError.message : 'Failed to load dashboard';
    return <PageError message={message} />;
  }

  const isLoading =
    health.isPending || queue.isPending || throughput.isPending || stats.isPending || history.isPending;

  if (isLoading) {
    return (
      <Root role="status" aria-live="polite" style={{ textAlign: 'center', color: '#8a8a9a' }}>
        Loading dashboard…
      </Root>
    );
  }

  if (!stats.data) {
    return (
      <Root>
        <EmptyState icon={undefined} heading="No sync data available" />
      </Root>
    );
  }

  const { syncStats } = stats.data;
  const allRecords = history.data ?? [];
  const now = Date.now();
  const last24h = now - 24 * 60 * 60 * 1000;
  const displayRecords = errorsOnly
    ? allRecords.filter(
        (r) => r.status === 'error' && new Date(r.started_at).getTime() >= last24h,
      )
    : allRecords;

  const queueData = queue.data;
  const queueAgeMin = oldestQueuedAge(queueData?.oldestQueuedAt ?? null);
  const tp = throughput.data;

  const healthMap = Object.fromEntries(
    (health.data ?? []).map((e) => [e.source, e]),
  );

  const domains = tp
    ? ([
        { key: 'messages', icon: '💬', label: 'iMessages', total: tp.totals.imessages, delta: tp.imessages },
        { key: 'mail',     icon: '✉️',  label: 'Mail',      total: tp.totals.mail,      delta: tp.mail },
        { key: 'contacts', icon: '👤', label: 'Contacts',  total: tp.totals.contacts,  delta: tp.contacts },
        { key: 'photos',   icon: '🖼️', label: 'Photos',    total: tp.totals.photos,    delta: tp.photos },
        { key: 'calendar', icon: '📅', label: 'Cal Events',total: tp.totals.events,    delta: tp.events },
      ] as const)
    : [];

  return (
    <Root>
      {/* Native Subsystems */}
      {diagnostics.data && <NativeSubsystemsCard data={diagnostics.data} />}

      {/* Domain KPI Tiles */}
      {domains.length > 0 && (
        <DomainGrid>
          {domains.map(({ key, icon, label, total, delta }) => {
            const h = healthMap[key];
            const isImessage = key === 'messages';
            return (
              <DomainTile key={key}>
                <DomainTileHeader>
                  <DomainIcon>{icon}</DomainIcon>
                  <DomainName>{label}</DomainName>
                </DomainTileHeader>
                <DomainTotal $zero={total === 0}>{total.toLocaleString()}</DomainTotal>
                <DomainDelta $nonzero={delta > 0}>+{delta.toLocaleString()} / 24h</DomainDelta>
                <DomainHealthRow>
                  <DomainHealthDot $status={h?.status} />
                  <DomainHealthText $status={h?.status}>
                    {h ? `${h.status} · ${relativeTime(h.lastSuccessAt)}` : 'no data'}
                  </DomainHealthText>
                </DomainHealthRow>
                {isImessage && queueData && (
                  <>
                    <OutboundBar>
                      <OutboundStat>
                        <OutboundVal $alert={queueData.queued > 0}>{queueData.queued}</OutboundVal>
                        <OutboundKey>queued</OutboundKey>
                      </OutboundStat>
                      <OutboundStat>
                        <OutboundVal $alert={queueData.failed > 0}>{queueData.failed}</OutboundVal>
                        <OutboundKey>failed</OutboundKey>
                      </OutboundStat>
                      <OutboundStat>
                        <OutboundVal $positive={queueData.sentLastHour > 0}>{queueData.sentLastHour}</OutboundVal>
                        <OutboundKey>sent / 1h</OutboundKey>
                      </OutboundStat>
                    </OutboundBar>
                    {queueData.oldestQueuedAt && queueAgeMin > 5 && (
                      <StallNote>stalled · {relativeTime(queueData.oldestQueuedAt)}</StallNote>
                    )}
                    {queueData.failed > 0 && failedSends.data && failedSends.data.length > 0 && (
                      <FailedList>
                        {failedSends.data.map((item) => (
                          <FailedItem key={item.id}>
                            <FailedTo title={item.toHandle}>{item.toHandle}</FailedTo>
                            <FailedReason>{item.failureReason ?? 'Unknown error'}</FailedReason>
                            <RetryButton
                              $loading={retrySendMutation.isPending}
                              disabled={retrySendMutation.isPending}
                              onClick={() => retrySendMutation.mutate(item.id)}
                            >
                              Retry
                            </RetryButton>
                          </FailedItem>
                        ))}
                      </FailedList>
                    )}
                  </>
                )}
              </DomainTile>
            );
          })}
        </DomainGrid>
      )}

      {/* Recent Errors / History */}
      <Card id="sync-history">
        <HistoryControls>
          <CardTitle style={{ margin: 0 }}>
            {errorsOnly ? 'Recent Errors (last 24h)' : 'Sync History'}
          </CardTitle>
          <FilterToggle $active={errorsOnly} onClick={() => setErrorsOnly((v) => !v)}>
            {errorsOnly ? 'Errors only' : 'All records'}
          </FilterToggle>
        </HistoryControls>

        {displayRecords.length === 0 ? (
          <p style={{ color: '#8a8a9a', margin: 0 }}>
            {errorsOnly ? 'No errors in the last 24h' : 'No sync history yet'}
          </p>
        ) : (
          <HistoryTable>
            <HistoryHeader>
              <div>Module</div>
              <div>Started</div>
              <div>Duration</div>
              <div>Status</div>
              <div>Messages</div>
              <div>Contacts</div>
              <div>Error</div>
            </HistoryHeader>
            {displayRecords.map((record) => (
              <HistoryRow key={record.id} id={`history-module-${record.module}`}>
                <div>{record.module}</div>
                <div style={{ fontSize: 12 }}>{formatDate(record.started_at)}</div>
                <div style={{ fontSize: 12 }}>
                  {formatDuration(record.started_at, record.completed_at)}
                </div>
                <div>
                  <Badge $status={record.status}>{record.status}</Badge>
                </div>
                <div>{record.messages_synced}</div>
                <div>{record.contacts_synced}</div>
                <div
                  style={{
                    fontSize: 11,
                    color: '#e05a5a',
                    maxWidth: 150,
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                  }}
                >
                  {record.error_message ?? '—'}
                </div>
              </HistoryRow>
            ))}
          </HistoryTable>
        )}

        <CumulativeFooter>
          <FooterStat>
            Total runs: <strong>{syncStats.total_syncs}</strong>
          </FooterStat>
          <FooterStat>
            Successful: <strong>{syncStats.successful_syncs}</strong>
          </FooterStat>
          <FooterStat>
            Failed: <strong>{syncStats.failed_syncs}</strong>
          </FooterStat>
          <FooterStat>
            Last run: <strong>{formatDate(syncStats.last_sync_at)}</strong>
          </FooterStat>
        </CumulativeFooter>
      </Card>

      {/* Live Activity Feed */}
      <Card>
        <CardTitle>Live Activity</CardTitle>
        {!activity.data || activity.data.length === 0 ? (
          <p style={{ color: '#8a8a9a', margin: 0 }}>No activity yet</p>
        ) : (
          <ActivityFeed>
            {activity.data.map((entry: ActivityEntry, i: number) => (
              <ActivityRow key={i} $level={entry.level}>
                <ActivityLevel $level={entry.level}>{entry.level}</ActivityLevel>
                <ActivityMsg title={entry.message}>{entry.message}</ActivityMsg>
              </ActivityRow>
            ))}
          </ActivityFeed>
        )}
      </Card>
    </Root>
  );
}
