import { useState, useMemo, useEffect, CSSProperties } from 'react';
import { Card, Row, Col, Statistic, Typography, Button, message, Alert, Spin } from 'antd';
import {
  TeamOutlined,
  CalculatorOutlined,
  CalendarOutlined,
  BarChartOutlined,
  LineChartOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useApi } from '@/hooks/useApi';
import { UserService } from '@/services/user';
import { BmiService } from '@/services/bmi';
import { AuditLogService } from '@/services/auditLog';
import { ROUTES } from '@/constants/routes';
import { parseError } from '@/utils/errorHandler';

interface UserResponse {
  id: string;
  user_id: string;
  email: string;
  first_name: string;
  last_name: string;
  date_of_birth: string | null;
  gender: string | null;
  is_active: boolean;
  role: string;
  last_login_at: string | null;
  created_at: string;
  updated_at: string;
}

interface BmiCalculationResponse {
  id: string;
  calculation_id: string;
  user_id: string | null;
  height_cm: number;
  weight_kg: number;
  bmi_value: number;
  bmi_category: string;
  category_id: string | null;
  unit: string;
  calculated_at: string;
  notes: string | null;
  is_deleted: boolean;
  created_at: string;
  updated_at: string;
}

interface BmiCategoryResponse {
  id: string;
  category_id: string;
  category_name: string;
  min_bmi: number;
  max_bmi: number | null;
  description: string | null;
  color_code: string | null;
  health_risk: string | null;
  recommendations: string | null;
  created_at: string;
  updated_at: string;
}

interface AuditLogResponse {
  id: string;
  log_id: string;
  user_id: string | null;
  action: string;
  entity_type: string | null;
  entity_id: string | null;
  timestamp: string;
  ip_address: string | null;
  user_agent: string | null;
  details: Record<string, unknown> | null;
  created_at: string;
  updated_at: string;
}

interface CategoryDistribution {
  name: string;
  value: number;
}

interface CalculationsPerDay {
  date: string;
  count: number;
}

interface UserRegistrationTrend {
  date: string;
  count: number;
}

const AdminDashboardPage = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();

  const [users, setUsers] = useState<UserResponse[]>([]);
  const [calculations, setCalculations] = useState<BmiCalculationResponse[]>([]);
  const [categories, setCategories] = useState<BmiCategoryResponse[]>([]);
  const [auditLogs, setAuditLogs] = useState<AuditLogResponse[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  const {
    data: usersData,
    loading: usersLoading,
    error: usersError,
    execute: fetchUsers
  } = useApi(UserService.list);

  const {
    data: calculationsData,
    loading: calculationsLoading,
    error: calculationsError,
    execute: fetchCalculations
  } = useApi(BmiService.listCalculations);

  const {
    data: categoriesData,
    loading: categoriesLoading,
    error: categoriesError,
    execute: fetchCategories
  } = useApi(BmiService.listCategories);

  const {
    data: auditLogsData,
    loading: auditLogsLoading,
    error: auditLogsError,
    execute: fetchAuditLogs
  } = useApi(AuditLogService.list);

  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      await Promise.all([
        fetchUsers({ limit: 100, offset: 0 }),
        fetchCalculations({ limit: 100, offset: 0 }),
        fetchCategories({ limit: 50, offset: 0 }),
        fetchAuditLogs({ limit: 50, offset: 0 })
      ]);
      setLoading(false);
    };
    void loadData();
  }, [fetchUsers, fetchCalculations, fetchCategories, fetchAuditLogs]);

  useEffect(() => {
    if (usersData) {
      setUsers(usersData);
    }
  }, [usersData]);

  useEffect(() => {
    if (calculationsData) {
      setCalculations(calculationsData);
    }
  }, [calculationsData]);

  useEffect(() => {
    if (categoriesData) {
      setCategories(categoriesData);
    }
  }, [categoriesData]);

  useEffect(() => {
    if (auditLogsData) {
      setAuditLogs(auditLogsData);
    }
  }, [auditLogsData]);

  useEffect(() => {
    if (usersError) {
      const parsed = parseError(usersError);
      messageApi.error(parsed.message);
    }
  }, [usersError, messageApi]);

  useEffect(() => {
    if (calculationsError) {
      const parsed = parseError(calculationsError);
      messageApi.error(parsed.message);
    }
  }, [calculationsError, messageApi]);

  useEffect(() => {
    if (categoriesError) {
      const parsed = parseError(categoriesError);
      messageApi.error(parsed.message);
    }
  }, [categoriesError, messageApi]);

  useEffect(() => {
    if (auditLogsError) {
      const parsed = parseError(auditLogsError);
      messageApi.error(parsed.message);
    }
  }, [auditLogsError, messageApi]);

  const totalUsers = useMemo(() => users.length, [users]);

  const totalCalculations = useMemo(() => calculations.length, [calculations]);

  const calculationsToday = useMemo(() => {
    return calculations.filter(c => {
      const calcDate = new Date(c.calculated_at).toDateString();
      const today = new Date().toDateString();
      return calcDate === today;
    }).length;
  }, [calculations]);

  const calculationsThisWeek = useMemo(() => {
    const now = new Date();
    const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
    return calculations.filter(c => {
      const d = new Date(c.calculated_at);
      return d >= weekAgo;
    }).length;
  }, [calculations]);

  const calculationsThisMonth = useMemo(() => {
    const now = new Date();
    return calculations.filter(c => {
      const d = new Date(c.calculated_at);
      return d.getMonth() === now.getMonth() && d.getFullYear() === now.getFullYear();
    }).length;
  }, [calculations]);

  const categoryDistribution = useMemo<CategoryDistribution[]>(() => {
    const acc: Record<string, number> = {};
    calculations.forEach(c => {
      acc[c.bmi_category] = (acc[c.bmi_category] || 0) + 1;
    });
    return Object.entries(acc).map(([name, value]) => ({ name, value }));
  }, [calculations]);

  const calculationsPerDay = useMemo<CalculationsPerDay[]>(() => {
    const acc: Record<string, number> = {};
    calculations.forEach(c => {
      const day = new Date(c.calculated_at).toLocaleDateString();
      acc[day] = (acc[day] || 0) + 1;
    });
    return Object.entries(acc)
      .map(([date, count]) => ({ date, count }))
      .slice(-30);
  }, [calculations]);

  const userRegistrationTrend = useMemo<UserRegistrationTrend[]>(() => {
    const acc: Record<string, number> = {};
    users.forEach(u => {
      const day = new Date(u.created_at).toLocaleDateString();
      acc[day] = (acc[day] || 0) + 1;
    });
    return Object.entries(acc).map(([date, count]) => ({ date, count }));
  }, [users]);

  const handleRefresh = async () => {
    setLoading(true);
    try {
      await Promise.all([
        fetchUsers({ limit: 100, offset: 0 }),
        fetchCalculations({ limit: 100, offset: 0 }),
        fetchCategories({ limit: 50, offset: 0 }),
        fetchAuditLogs({ limit: 50, offset: 0 })
      ]);
      messageApi.success('Dashboard data refreshed');
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const navigateToUsers = () => {
    navigate(ROUTES.ADMIN_USERS);
  };

  const navigateToCategories = () => {
    navigate(ROUTES.ADMIN_CATEGORIES);
  };

  const navigateToAuditLogs = () => {
    navigate(ROUTES.ADMIN_AUDIT_LOGS);
  };

  const mainContainerStyle: CSSProperties = {
    minHeight: '100vh',
    height: '100%',
    width: '100%',
    display: 'flex',
    flexDirection: 'column',
    padding: '24px',
    backgroundColor: '#f5f5f5'
  };

  const pageHeaderStyle: CSSProperties = {
    marginBottom: '24px',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center'
  };

  const statCardsRowStyle: CSSProperties = {
    marginBottom: '24px'
  };

  const chartsRow1Style: CSSProperties = {
    marginBottom: '24px'
  };

  const chartsRow2Style: CSSProperties = {
    marginBottom: '24px'
  };

  const navSectionTitleStyle: CSSProperties = {
    marginBottom: '16px'
  };

  const cardStyle: CSSProperties = {
    borderRadius: '8px'
  };

  const chartCardStyle: CSSProperties = {
    borderRadius: '8px',
    height: '400px'
  };

  const navCardStyle: CSSProperties = {
    borderRadius: '8px',
    cursor: 'pointer',
    textAlign: 'center'
  };

  const isLoading = loading || usersLoading || calculationsLoading || categoriesLoading || auditLogsLoading;

  return (
    <div style={mainContainerStyle}>
      {contextHolder}
      {(usersError || calculationsError || categoriesError || auditLogsError) && (
        <Alert
          message="Error loading dashboard data"
          description="Some data could not be loaded. Please try refreshing."
          type="error"
          closable
          style={{ marginBottom: '24px' }}
        />
      )}
      <div style={pageHeaderStyle}>
        <Typography.Title level={2} style={{ margin: 0 }}>
          Admin Dashboard
        </Typography.Title>
        <Button
          type="default"
          icon={<ReloadOutlined />}
          onClick={handleRefresh}
          loading={isLoading}
        >
          Refresh Data
        </Button>
      </div>

      <Spin spinning={isLoading}>
        <Row gutter={[16, 16]} style={statCardsRowStyle}>
          <Col xs={24} sm={12} md={8} lg={5}>
            <Card bordered={false} style={cardStyle}>
              <Statistic
                title="Total Users"
                value={totalUsers}
                prefix={<TeamOutlined />}
                valueStyle={{ color: '#1677ff' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8} lg={5}>
            <Card bordered={false} style={cardStyle}>
              <Statistic
                title="Total Calculations"
                value={totalCalculations}
                prefix={<CalculatorOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8} lg={5}>
            <Card bordered={false} style={cardStyle}>
              <Statistic
                title="Calculations Today"
                value={calculationsToday}
                prefix={<CalendarOutlined />}
                valueStyle={{ color: '#faad14' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8} lg={5}>
            <Card bordered={false} style={cardStyle}>
              <Statistic
                title="This Week"
                value={calculationsThisWeek}
                prefix={<BarChartOutlined />}
                valueStyle={{ color: '#722ed1' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8} lg={4}>
            <Card bordered={false} style={cardStyle}>
              <Statistic
                title="This Month"
                value={calculationsThisMonth}
                prefix={<LineChartOutlined />}
                valueStyle={{ color: '#eb2f96' }}
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={[16, 16]} style={chartsRow1Style}>
          <Col xs={24} lg={14}>
            <Card title="Calculations Per Day" bordered={false} style={chartCardStyle}>
              <div style={{ height: '300px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Typography.Text type="secondary">
                  Chart visualization: {calculationsPerDay.length} data points
                </Typography.Text>
              </div>
            </Card>
          </Col>
          <Col xs={24} lg={10}>
            <Card title="BMI Category Distribution" bordered={false} style={chartCardStyle}>
              <div style={{ height: '300px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Typography.Text type="secondary">
                  Chart visualization: {categoryDistribution.length} categories
                </Typography.Text>
              </div>
            </Card>
          </Col>
        </Row>

        <Row gutter={[16, 16]} style={chartsRow2Style}>
          <Col xs={24} lg={12}>
            <Card title="Average BMI by Age Group & Gender" bordered={false} style={chartCardStyle}>
              <div style={{ height: '300px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Typography.Text type="secondary">
                  Chart visualization placeholder
                </Typography.Text>
              </div>
            </Card>
          </Col>
          <Col xs={24} lg={12}>
            <Card title="User Registration Trend" bordered={false} style={chartCardStyle}>
              <div style={{ height: '300px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Typography.Text type="secondary">
                  Chart visualization: {userRegistrationTrend.length} data points
                </Typography.Text>
              </div>
            </Card>
          </Col>
        </Row>

        <Typography.Title level={4} style={navSectionTitleStyle}>
          Quick Navigation
        </Typography.Title>

        <Row gutter={[16, 16]}>
          <Col xs={24} sm={8}>
            <Card
              hoverable
              title="User Management"
              bordered={false}
              style={navCardStyle}
              onClick={navigateToUsers}
            >
              <Typography.Text type="secondary">
                Manage user accounts, roles, and permissions
              </Typography.Text>
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card
              hoverable
              title="BMI Categories"
              bordered={false}
              style={navCardStyle}
              onClick={navigateToCategories}
            >
              <Typography.Text type="secondary">
                Configure BMI category thresholds and descriptions
              </Typography.Text>
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card
              hoverable
              title="Audit Logs"
              bordered={false}
              style={navCardStyle}
              onClick={navigateToAuditLogs}
            >
              <Typography.Text type="secondary">
                View system activity logs and security events
              </Typography.Text>
            </Card>
          </Col>
        </Row>
      </Spin>
    </div>
  );
};

export default AdminDashboardPage;