import { useEffect, useState, useCallback } from 'react';
import { Card, Row, Col, Statistic, Spin, Typography, Grid, Button, App } from 'antd';
import {
  CheckCircleOutlined,
  WarningOutlined,
  InfoCircleOutlined,
  EnvironmentOutlined,
  ReloadOutlined,
  BarChartOutlined,
} from '@ant-design/icons';
import { useOutletContext } from 'react-router-dom';
import { api } from '@/lib/api';
import type { AppOutletContext } from '@/components/AppLayout';
import type { LocationStats } from '@/types/api';

const { Title, Text } = Typography;

export default function DataQualityDashboardPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const { message } = App.useApp();
  const screens = Grid.useBreakpoint();

  const [stats, setStats] = useState<LocationStats | null>(null);
  const [loading, setLoading] = useState(true);

  const loadStats = useCallback(async () => {
    try {
      const { data } = await api.get<LocationStats>('/map/locations/stats');
      setStats(data);
    } catch {
      message.error('Failed to load data quality stats');
    } finally {
      setLoading(false);
    }
  }, [message]);

  // Initial load + auto-refresh every 30s
  useEffect(() => {
    loadStats();
    const interval = setInterval(loadStats, 30000);
    return () => clearInterval(interval);
  }, [loadStats]);

  useEffect(() => {
    setPageHeader({ title: 'Data Quality Dashboard' });
    return () => setPageHeader(null);
  }, [setPageHeader]);

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

  if (!stats) return null;

  return (
    <div style={{ padding: screens.md ? 24 : 16 }}>
      <div style={{ marginBottom: 16 }}>
        <Button
          icon={<ReloadOutlined />}
          onClick={() => {
            setLoading(true);
            loadStats();
          }}
        >
          Refresh
        </Button>
      </div>

      {/* Overview Cards */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="Total Locations"
              value={stats.total}
              prefix={<EnvironmentOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="Geocoded"
              value={stats.geocoded}
              suffix={
                <Text type="secondary" style={{ fontSize: 12 }}>
                  ({stats.total > 0 ? Math.round((stats.geocoded / stats.total) * 100) : 0}%)
                </Text>
              }
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="Ungeocoded"
              value={stats.ungeocoded}
              valueStyle={{ color: stats.ungeocoded > 0 ? '#ff4d4f' : '#8c8c8c' }}
              prefix={stats.ungeocoded > 0 ? <WarningOutlined /> : undefined}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="Average Confidence"
              value={stats.confidence.average ?? 0}
              suffix="%"
              valueStyle={{
                color:
                  !stats.confidence.average
                    ? '#8c8c8c'
                    : stats.confidence.average >= 85
                    ? '#52c41a'
                    : stats.confidence.average >= 60
                    ? '#faad14'
                    : '#ff4d4f',
              }}
            />
          </Card>
        </Col>
      </Row>

      {/* Geocoding Confidence */}
      <Title level={5} style={{ marginTop: 16, marginBottom: 12 }}>
        <BarChartOutlined /> Geocoding Confidence
      </Title>
      <Row gutter={[12, 12]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="High Confidence"
              value={stats.confidence.high}
              prefix={<CheckCircleOutlined />}
              suffix={<Text type="secondary" style={{ fontSize: 12 }}>≥85%</Text>}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="Medium Confidence"
              value={stats.confidence.medium}
              prefix={<InfoCircleOutlined />}
              suffix={<Text type="secondary" style={{ fontSize: 12 }}>60-84%</Text>}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="Low Confidence"
              value={stats.confidence.low}
              prefix={<WarningOutlined />}
              suffix={<Text type="secondary" style={{ fontSize: 12 }}>&lt;60%</Text>}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="Manual/None"
              value={stats.confidence.none}
              valueStyle={{ color: '#8c8c8c' }}
            />
          </Card>
        </Col>
      </Row>

      {/* Provider Breakdown */}
      <Title level={5} style={{ marginTop: 16, marginBottom: 12 }}>
        Provider Distribution
      </Title>
      <Row gutter={[12, 12]} style={{ marginBottom: 24 }}>
        {Object.entries(stats.providers).map(([provider, count]) => (
          <Col xs={24} sm={12} md={6} key={provider}>
            <Card size="small">
              <Statistic
                title={provider.charAt(0).toUpperCase() + provider.slice(1)}
                value={count}
                valueStyle={{ fontSize: 18 }}
              />
            </Card>
          </Col>
        ))}
      </Row>

      {/* Building Type Distribution */}
      <Title level={5} style={{ marginTop: 16, marginBottom: 12 }}>
        Building Types
      </Title>
      <Row gutter={[12, 12]}>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="Single Family"
              value={stats.buildingTypes.SINGLE_FAMILY}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="Multi-Unit"
              value={stats.buildingTypes.MULTI_UNIT}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="Mixed Use"
              value={stats.buildingTypes.MIXED_USE}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="Commercial"
              value={stats.buildingTypes.COMMERCIAL}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
}
