import { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic, Table, Tag, Typography, Spin, Grid, App } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import type { MyCanvassStats, CanvassVisit } from '@/types/canvass';
import { VISIT_OUTCOME_LABELS, VISIT_OUTCOME_COLORS, type VisitOutcome } from '@/types/canvass';
import type { PaginationMeta } from '@/types/api';

export default function MyActivityPage() {
  const { message } = App.useApp();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  const [stats, setStats] = useState<MyCanvassStats | null>(null);
  const [visits, setVisits] = useState<CanvassVisit[]>([]);
  const [pagination, setPagination] = useState<PaginationMeta | null>(null);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);

  useEffect(() => {
    const load = async () => {
      setLoading(true);
      try {
        const [statsRes, visitsRes] = await Promise.all([
          api.get('/map/canvass/my/stats'),
          api.get('/map/canvass/my/visits', { params: { page, limit: 20 } }),
        ]);
        setStats(statsRes.data);
        setVisits(visitsRes.data.visits);
        setPagination(visitsRes.data.pagination);
      } catch {
        message.error('Failed to load activity');
      } finally {
        setLoading(false);
      }
    };
    load();
  }, [page]); // eslint-disable-line react-hooks/exhaustive-deps

  const columns: ColumnsType<CanvassVisit> = [
    {
      title: 'Address',
      key: 'address',
      render: (_: unknown, record: CanvassVisit) => (
        <span>
          {record.address?.location?.address ?? 'Unknown'}
          {record.address?.unitNumber && ` #${record.address.unitNumber}`}
        </span>
      ),
    },
    {
      title: 'Outcome',
      dataIndex: 'outcome',
      key: 'outcome',
      render: (outcome: VisitOutcome) => (
        <Tag color={VISIT_OUTCOME_COLORS[outcome]}>
          {VISIT_OUTCOME_LABELS[outcome]}
        </Tag>
      ),
    },
    {
      title: 'When',
      dataIndex: 'visitedAt',
      key: 'visitedAt',
      render: (val: string) => dayjs(val).format('MMM D, h:mm A'),
    },
  ];

  if (loading && !stats) {
    return <div style={{ textAlign: 'center', padding: 48 }}><Spin size="large" /></div>;
  }

  // Outcome breakdown
  const outcomeEntries = stats?.byOutcome
    ? Object.entries(stats.byOutcome).sort((a, b) => b[1] - a[1])
    : [];

  return (
    <div>
      <Typography.Title level={3} style={{ marginBottom: 16 }}>My Activity</Typography.Title>

      <Row gutter={[12, 12]} style={{ marginBottom: 24 }}>
        <Col xs={12} md={8}>
          <Card size="small">
            <Statistic title="Today" value={stats?.todayVisits ?? 0} />
          </Card>
        </Col>
        <Col xs={12} md={8}>
          <Card size="small">
            <Statistic title="Total Doors" value={stats?.totalVisits ?? 0} />
          </Card>
        </Col>
        <Col xs={24} md={8}>
          <Card size="small">
            <Statistic title="Sessions" value={stats?.sessions ?? 0} />
          </Card>
        </Col>
      </Row>

      {outcomeEntries.length > 0 && (
        <Card size="small" title="Outcome Breakdown" style={{ marginBottom: 24 }}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {outcomeEntries.map(([key, count]) => (
              <Tag
                key={key}
                color={VISIT_OUTCOME_COLORS[key as VisitOutcome]}
                style={{ fontSize: 13 }}
              >
                {VISIT_OUTCOME_LABELS[key as VisitOutcome]}: {count}
              </Tag>
            ))}
          </div>
        </Card>
      )}

      <Card title="Visit History" size="small">
        <Table
          dataSource={visits}
          columns={columns}
          rowKey="id"
          size="small"
          scroll={isMobile ? { x: 500 } : undefined}
          loading={loading}
          pagination={{
            current: page,
            total: pagination?.total ?? 0,
            pageSize: 20,
            showSizeChanger: false,
            onChange: setPage,
          }}
        />
      </Card>
    </div>
  );
}
