import { useState, useCallback, useEffect } from 'react';
import { Drawer, Table, DatePicker, Select, Button, Space, Typography, Tag, Grid } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { HistoryOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import { api } from '@/lib/api';
import type { TrackingSessionSummary, SessionRoute } from '@/types/tracking';
import type { PaginationMeta } from '@/types/api';

dayjs.extend(duration);

interface HistoricalRoutesDrawerProps {
  open: boolean;
  onClose: () => void;
  onSelectRoute: (route: SessionRoute | null) => void;
  volunteers: { userId: string; name: string | null; email: string }[];
}

export default function HistoricalRoutesDrawer({
  open,
  onClose,
  onSelectRoute,
  volunteers,
}: HistoricalRoutesDrawerProps) {
  const [sessions, setSessions] = useState<TrackingSessionSummary[]>([]);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [pagination, setPagination] = useState<PaginationMeta | null>(null);
  const [loading, setLoading] = useState(false);
  const [routeLoading, setRouteLoading] = useState<string | null>(null);
  const [selectedId, setSelectedId] = useState<string | null>(null);

  // Filters
  const [userId, setUserId] = useState<string | undefined>(undefined);
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);
  const [page, setPage] = useState(1);

  const fetchSessions = useCallback(async () => {
    setLoading(true);
    try {
      const params: Record<string, string> = { page: page.toString(), limit: '15' };
      if (userId) params.userId = userId;
      if (dateRange?.[0]) params.from = dateRange[0].startOf('day').toISOString();
      if (dateRange?.[1]) params.to = dateRange[1].endOf('day').toISOString();

      const { data } = await api.get('/map/tracking/sessions', { params });
      setSessions(data.sessions);
      setPagination(data.pagination);
    } catch {
      // Silent
    } finally {
      setLoading(false);
    }
  }, [page, userId, dateRange]);

  useEffect(() => {
    if (open) fetchSessions();
  }, [open, fetchSessions]);

  const handleViewRoute = async (sessionId: string) => {
    if (selectedId === sessionId) {
      setSelectedId(null);
      onSelectRoute(null);
      return;
    }

    setRouteLoading(sessionId);
    try {
      const { data } = await api.get(`/map/tracking/sessions/${sessionId}/route`);
      setSelectedId(sessionId);
      onSelectRoute(data);
    } catch {
      // Silent
    } finally {
      setRouteLoading(null);
    }
  };

  const formatDuration = (startedAt: string, endedAt: string | null) => {
    if (!endedAt) return 'Active';
    const dur = dayjs.duration(dayjs(endedAt).diff(dayjs(startedAt)));
    const hours = Math.floor(dur.asHours());
    const mins = dur.minutes();
    return hours > 0 ? `${hours}h ${mins}m` : `${mins}m`;
  };

  const formatDistance = (meters: number) => {
    if (meters >= 1000) return `${(meters / 1000).toFixed(1)} km`;
    return `${Math.round(meters)} m`;
  };

  const columns: ColumnsType<TrackingSessionSummary> = [
    {
      title: 'Volunteer',
      key: 'volunteer',
      render: (_: unknown, r: TrackingSessionSummary) => r.userName || r.userEmail,
      ellipsis: true,
    },
    {
      title: 'Date',
      dataIndex: 'startedAt',
      key: 'date',
      render: (val: string) => dayjs(val).format('MMM D, h:mm A'),
      width: 140,
    },
    {
      title: 'Duration',
      key: 'duration',
      render: (_: unknown, r: TrackingSessionSummary) => formatDuration(r.startedAt, r.endedAt),
      width: 80,
    },
    {
      title: 'Distance',
      dataIndex: 'totalDistanceM',
      key: 'distance',
      render: (val: number) => formatDistance(val),
      width: 80,
    },
    {
      title: 'Points',
      dataIndex: 'totalPoints',
      key: 'points',
      width: 60,
    },
    {
      title: '',
      key: 'actions',
      width: 80,
      render: (_: unknown, r: TrackingSessionSummary) => (
        <Button
          size="small"
          type={selectedId === r.id ? 'primary' : 'default'}
          loading={routeLoading === r.id}
          onClick={() => handleViewRoute(r.id)}
        >
          {selectedId === r.id ? 'Hide' : 'View'}
        </Button>
      ),
    },
  ];

  return (
    <Drawer
      title={<><HistoryOutlined /> Route History</>}
      placement="right"
      width={isMobile ? '100%' : 600}
      open={open}
      onClose={() => {
        onClose();
        onSelectRoute(null);
        setSelectedId(null);
      }}
    >
      <Space style={{ marginBottom: 16 }} wrap>
        <Select
          placeholder="All volunteers"
          allowClear
          style={{ width: 180 }}
          value={userId}
          onChange={(v) => { setUserId(v); setPage(1); }}
          options={volunteers.map((v) => ({
            label: v.name || v.email,
            value: v.userId,
          }))}
        />
        <DatePicker.RangePicker
          value={dateRange}
          onChange={(val) => { setDateRange(val as [dayjs.Dayjs, dayjs.Dayjs] | null); setPage(1); }}
          style={{ width: 240 }}
        />
      </Space>

      {selectedId && (
        <Tag color="blue" closable onClose={() => { setSelectedId(null); onSelectRoute(null); }} style={{ marginBottom: 12 }}>
          Showing route on map
        </Tag>
      )}

      <Table
        dataSource={sessions}
        columns={columns}
        rowKey="id"
        size="small"
        loading={loading}
        pagination={
          pagination
            ? {
                current: pagination.page,
                pageSize: pagination.limit,
                total: pagination.total,
                showSizeChanger: false,
                onChange: (p) => setPage(p),
              }
            : false
        }
        rowClassName={(r) => (r.id === selectedId ? 'ant-table-row-selected' : '')}
      />

      {sessions.length === 0 && !loading && (
        <Typography.Text type="secondary" style={{ display: 'block', textAlign: 'center', marginTop: 24 }}>
          No tracking sessions found
        </Typography.Text>
      )}
    </Drawer>
  );
}
