import { useEffect, useState, useCallback, useRef } from 'react';
import { Typography, Row, Col, Button, Statistic, Card, Empty, Spin, message, Tag, List } from 'antd';
import {
  PlusOutlined,
  CloudServerOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  HeartOutlined,
  ExclamationCircleOutlined,
  SyncOutlined,
  BellOutlined,
  CloseCircleOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import InstanceCard from '@/components/InstanceCard';
import type { Instance, EventSummary } from '@/types/api';

interface HealthOverviewItem {
  id: string;
  name: string;
  slug: string;
  domain: string;
  status: string;
  lastHealthCheck?: string;
  health?: { status: string; healthyServices: number; totalServices: number } | null;
}

const AUTO_REFRESH_INTERVAL = 30_000;

export default function DashboardPage() {
  const navigate = useNavigate();
  const [instances, setInstances] = useState<Instance[]>([]);
  const [healthOverview, setHealthOverview] = useState<HealthOverviewItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
  const [secondsAgo, setSecondsAgo] = useState(0);
  const lastUpdatedRef = useRef<Date | null>(null);

  const [eventSummary, setEventSummary] = useState<EventSummary | null>(null);

  const fetchEventSummary = useCallback(async () => {
    try {
      const { data } = await api.get('/events/summary');
      setEventSummary(data.data);
    } catch {
      // Silently fail — events are supplementary
    }
  }, []);

  const fetchInstances = useCallback(async () => {
    try {
      const { data } = await api.get('/instances');
      setInstances(data.data);
    } catch {
      message.error('Failed to load instances');
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchHealthOverview = useCallback(async () => {
    try {
      const { data } = await api.get('/health/overview');
      setHealthOverview(data.data);
    } catch {
      message.error('Failed to load health overview');
    }
  }, []);

  const refreshAll = useCallback(async () => {
    await Promise.all([fetchInstances(), fetchHealthOverview(), fetchEventSummary()]);
    const now = new Date();
    setLastUpdated(now);
    lastUpdatedRef.current = now;
    setSecondsAgo(0);
  }, [fetchInstances, fetchHealthOverview, fetchEventSummary]);

  // Initial fetch
  useEffect(() => {
    refreshAll();
  }, [refreshAll]);

  // Auto-refresh every 30s
  useEffect(() => {
    const id = setInterval(refreshAll, AUTO_REFRESH_INTERVAL);
    return () => clearInterval(id);
  }, [refreshAll]);

  // Tick the "seconds ago" display every second
  useEffect(() => {
    const id = setInterval(() => {
      if (lastUpdatedRef.current) {
        setSecondsAgo(Math.floor((Date.now() - lastUpdatedRef.current.getTime()) / 1000));
      }
    }, 1000);
    return () => clearInterval(id);
  }, []);

  const handleStart = async (id: string) => {
    try {
      await api.post(`/instances/${id}/start`);
      message.success('Instance started');
      fetchInstances();
    } catch {
      message.error('Failed to start instance');
    }
  };

  const handleStop = async (id: string) => {
    try {
      await api.post(`/instances/${id}/stop`);
      message.success('Instance stopped');
      fetchInstances();
    } catch {
      message.error('Failed to stop instance');
    }
  };

  const running = instances.filter((i) => i.status === 'RUNNING').length;
  const stopped = instances.filter((i) => i.status === 'STOPPED').length;
  const errors = instances.filter((i) => i.status === 'ERROR').length;

  // Health stats from overview
  const healthyInstances = healthOverview.filter((h) => h.health?.status === 'HEALTHY').length;
  const degradedInstances = healthOverview.filter((h) => h.health?.status === 'DEGRADED').length;

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', padding: 100 }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <Typography.Title level={3} style={{ margin: 0 }}>
            Dashboard
          </Typography.Title>
          {lastUpdated && (
            <Typography.Text type="secondary" style={{ fontSize: 12 }}>
              <SyncOutlined style={{ marginRight: 4 }} />
              Updated {secondsAgo < 5 ? 'just now' : `${secondsAgo}s ago`}
            </Typography.Text>
          )}
        </div>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => navigate('/app/instances/new')}
        >
          Create Instance
        </Button>
      </div>

      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={12} sm={6} lg={4}>
          <Card>
            <Statistic
              title="Total Instances"
              value={instances.length}
              prefix={<CloudServerOutlined />}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6} lg={4}>
          <Card>
            <Statistic
              title="Running"
              value={running}
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6} lg={4}>
          <Card>
            <Statistic
              title="Healthy"
              value={healthyInstances}
              valueStyle={{ color: '#52c41a' }}
              prefix={<HeartOutlined />}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6} lg={4}>
          <Card>
            <Statistic
              title="Degraded"
              value={degradedInstances}
              valueStyle={degradedInstances > 0 ? { color: '#faad14' } : undefined}
              prefix={degradedInstances > 0 ? <ExclamationCircleOutlined /> : undefined}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6} lg={4}>
          <Card>
            <Statistic title="Stopped" value={stopped} />
          </Card>
        </Col>
        <Col xs={12} sm={6} lg={4}>
          <Card>
            <Statistic
              title="Errors"
              value={errors}
              valueStyle={errors > 0 ? { color: '#ff4d4f' } : undefined}
              prefix={errors > 0 ? <WarningOutlined /> : undefined}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6} lg={4}>
          <Card>
            <Statistic
              title="Unread Events"
              value={eventSummary?.total || 0}
              valueStyle={(eventSummary?.errors || 0) > 0 ? { color: '#ff4d4f' } : (eventSummary?.warnings || 0) > 0 ? { color: '#faad14' } : undefined}
              prefix={<BellOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* Recent Errors */}
      {eventSummary && eventSummary.recentErrors.length > 0 && (
        <Card
          title={
            <span>
              <CloseCircleOutlined style={{ color: '#ff4d4f', marginRight: 8 }} />
              Recent Events ({eventSummary.errors} error{eventSummary.errors !== 1 ? 's' : ''}, {eventSummary.warnings} warning{eventSummary.warnings !== 1 ? 's' : ''})
            </span>
          }
          size="small"
          style={{ marginBottom: 24 }}
        >
          <List
            size="small"
            dataSource={eventSummary.recentErrors}
            renderItem={(event) => (
              <List.Item
                style={{ cursor: 'pointer' }}
                onClick={() => navigate(`/app/instances/${event.instanceId}`)}
              >
                <List.Item.Meta
                  avatar={
                    <Tag color={event.severity === 'ERROR' ? 'red' : 'orange'}>
                      {event.severity}
                    </Tag>
                  }
                  title={
                    <span>
                      <Typography.Text strong>{event.instance?.name || 'Unknown'}</Typography.Text>
                      {' — '}
                      {event.title}
                    </span>
                  }
                  description={
                    <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                      {event.source} — {dayjs(event.createdAt).format('MM-DD HH:mm')}
                    </Typography.Text>
                  }
                />
              </List.Item>
            )}
          />
        </Card>
      )}

      {instances.length === 0 ? (
        <Empty
          description="No instances yet"
          style={{ padding: 60 }}
        >
          <Button type="primary" onClick={() => navigate('/app/instances/new')}>
            Create Your First Instance
          </Button>
        </Empty>
      ) : (
        <Row gutter={[16, 16]}>
          {instances.map((instance) => (
            <Col xs={24} sm={12} lg={8} xl={6} key={instance.id}>
              <InstanceCard
                instance={instance}
                onStart={handleStart}
                onStop={handleStop}
              />
            </Col>
          ))}
        </Row>
      )}
    </div>
  );
}
