import { useState, useMemo, useEffect, useCallback, CSSProperties } from 'react';
import { Layout, Card, Row, Col, Typography, Tag, Progress, Button, List, Menu, message, Alert } from 'antd';
import { DashboardOutlined, CalculatorOutlined, HistoryOutlined, AimOutlined, UserOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useApi } from '@/hooks/useApi';
import { BmiCalculationService } from '@/services/bmiCalculation';
import { GoalService } from '@/services/goal';
import { ROUTES } from '@/constants/routes';
import { parseError } from '@/utils/errorHandler';
import { useAppContext } from '@/store/AppStore';

const { Sider, Content } = Layout;
const { Title, Text, Paragraph } = Typography;

interface BmiCalculation {
  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 Goal {
  id: string;
  goal_id: string;
  user_id: string;
  goal_type: string;
  target_value: number;
  current_value: number | null;
  start_date: string;
  target_date: string;
  status: string;
  created_at: string;
  updated_at: string;
}

interface TrendDataPoint {
  date: string;
  bmi: number;
}

const DashboardPage = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  const { currentUser } = useAppContext();

  const [recentCalculations, setRecentCalculations] = useState<BmiCalculation[]>([]);
  const [activeGoals, setActiveGoals] = useState<Goal[]>([]);
  const [loadingCalculations, setLoadingCalculations] = useState<boolean>(true);
  const [loadingGoals, setLoadingGoals] = useState<boolean>(true);

  const fetchCalculationsCallback = useCallback(async () => {
    if (!currentUser?.userId) {
      throw new Error('User ID not available');
    }
    return BmiCalculationService.list({
      user_id: currentUser.userId,
      is_deleted: false,
      limit: 20,
      offset: 0
    });
  }, [currentUser?.userId]);

  const fetchGoalsCallback = useCallback(async () => {
    if (!currentUser?.userId) {
      throw new Error('User ID not available');
    }
    return GoalService.getUserGoals(currentUser.userId, {
      status: 'ACTIVE',
      limit: 10,
      offset: 0
    });
  }, [currentUser?.userId]);

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

  const {
    data: goalsData,
    loading: goalsLoading,
    error: goalsError,
    execute: fetchGoals
  } = useApi(fetchGoalsCallback);

  useEffect(() => {
    if (currentUser?.userId) {
      void fetchCalculations();
      void fetchGoals();
    }
  }, [currentUser?.userId, fetchCalculations, fetchGoals]);

  useEffect(() => {
    if (calculationsData) {
      setRecentCalculations(calculationsData as BmiCalculation[]);
      setLoadingCalculations(false);
    }
  }, [calculationsData]);

  useEffect(() => {
    if (goalsData) {
      setActiveGoals(goalsData as Goal[]);
      setLoadingGoals(false);
    }
  }, [goalsData]);

  useEffect(() => {
    if (calculationsError) {
      const { message: errorMessage } = parseError(calculationsError);
      messageApi.error(errorMessage);
      setLoadingCalculations(false);
    }
  }, [calculationsError, messageApi]);

  useEffect(() => {
    if (goalsError) {
      const { message: errorMessage } = parseError(goalsError);
      messageApi.error(errorMessage);
      setLoadingGoals(false);
    }
  }, [goalsError, messageApi]);

  const latestCalculation = useMemo(() => {
    return recentCalculations.length > 0 ? recentCalculations[0] : null;
  }, [recentCalculations]);

  const currentBmiValue = useMemo(() => {
    return recentCalculations.length > 0 ? recentCalculations[0].bmi_value : null;
  }, [recentCalculations]);

  const currentBmiCategory = useMemo(() => {
    return recentCalculations.length > 0 ? recentCalculations[0].bmi_category : 'N/A';
  }, [recentCalculations]);

  const lastCalculationDate = useMemo(() => {
    return recentCalculations.length > 0 ? recentCalculations[0].calculated_at : null;
  }, [recentCalculations]);

  const totalCalculations = useMemo(() => {
    return recentCalculations.length;
  }, [recentCalculations]);

  const trendChartData = useMemo<TrendDataPoint[]>(() => {
    return recentCalculations.slice().reverse().map(c => ({ date: c.calculated_at, bmi: c.bmi_value }));
  }, [recentCalculations]);

  const goalProgress = useMemo(() => {
    if (activeGoals.length === 0) return 0;
    const firstGoal = activeGoals[0];
    return Math.round(((firstGoal.current_value || 0) / firstGoal.target_value) * 100);
  }, [activeGoals]);

  const handleNavigateToCalculator = useCallback(() => {
    navigate(ROUTES.HOME);
  }, [navigate]);

  const handleNavigateToHistory = useCallback(() => {
    navigate(ROUTES.HISTORY);
  }, [navigate]);

  const handleNavigateToGoals = useCallback(() => {
    navigate(ROUTES.GOALS);
  }, [navigate]);

  const handleNavigateToProfile = useCallback(() => {
    navigate(ROUTES.PROFILE);
  }, [navigate]);

  const handleViewFullHistory = useCallback(() => {
    navigate(ROUTES.HISTORY);
  }, [navigate]);

  const handleViewAllGoals = useCallback(() => {
    navigate(ROUTES.GOALS);
  }, [navigate]);

  const handleMenuClick = useCallback((e: { key: string }) => {
    switch (e.key) {
      case 'dashboard':
        navigate(ROUTES.DASHBOARD);
        break;
      case 'calculator':
        navigate(ROUTES.HOME);
        break;
      case 'history':
        navigate(ROUTES.HISTORY);
        break;
      case 'goals':
        navigate(ROUTES.GOALS);
        break;
      case 'profile':
        navigate(ROUTES.PROFILE);
        break;
    }
  }, [navigate]);

  const mainContainerStyle: CSSProperties = {
    minHeight: '100vh',
    height: '100%',
    width: '100%',
    display: 'flex',
    flexDirection: 'row'
  };

  const siderStyle: CSSProperties = {
    borderRight: '1px solid #f0f0f0',
    background: '#fff'
  };

  const contentAreaStyle: CSSProperties = {
    background: '#f5f5f5'
  };

  const pageHeaderStyle: CSSProperties = {
    padding: '24px 24px 0 24px'
  };

  const contentBodyStyle: CSSProperties = {
    padding: '24px'
  };

  const logoStyle: CSSProperties = {
    padding: '16px 24px',
    margin: 0,
    borderBottom: '1px solid #f0f0f0',
    color: '#1677ff'
  };

  const menuStyle: CSSProperties = {
    borderRight: 'none'
  };

  return (
    <div style={mainContainerStyle}>
      {contextHolder}
      <Sider
        width={240}
        collapsible
        breakpoint="md"
        collapsedWidth={0}
        theme="light"
        style={siderStyle}
      >
        <Title level={4} style={logoStyle}>
          BMI Calculator
        </Title>
        <Menu
          mode="inline"
          selectedKeys={['dashboard']}
          style={menuStyle}
          onClick={handleMenuClick}
          items={[
            {
              key: 'dashboard',
              icon: <DashboardOutlined />,
              label: 'Dashboard'
            },
            {
              key: 'calculator',
              icon: <CalculatorOutlined />,
              label: 'Calculator'
            },
            {
              key: 'history',
              icon: <HistoryOutlined />,
              label: 'History'
            },
            {
              key: 'goals',
              icon: <AimOutlined />,
              label: 'Goals'
            },
            {
              key: 'profile',
              icon: <UserOutlined />,
              label: 'Profile'
            }
          ]}
        />
      </Sider>
      <Layout style={contentAreaStyle}>
        <div style={pageHeaderStyle}>
          <Title level={3} style={{ marginBottom: 4 }}>
            Welcome back!
          </Title>
          <Text type="secondary">Here&apos;s your BMI health overview</Text>
        </div>
        <Content style={contentBodyStyle}>
          {calculationsError && (
            <Alert
              message="Error loading calculations"
              description={parseError(calculationsError).message}
              type="error"
              closable
              style={{ marginBottom: 16 }}
            />
          )}
          {goalsError && (
            <Alert
              message="Error loading goals"
              description={parseError(goalsError).message}
              type="error"
              closable
              style={{ marginBottom: 16 }}
            />
          )}
          <Row gutter={[16, 16]}>
            <Col xs={24} sm={12} md={12} lg={6}>
              <Card bordered={false} hoverable style={{ borderRadius: 8 }} loading={loadingCalculations}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                  <Text type="secondary" style={{ fontSize: 14 }}>
                    Current BMI
                  </Text>
                </div>
                <Title level={2} style={{ margin: 0, color: '#1677ff' }}>
                  {currentBmiValue !== null ? currentBmiValue.toFixed(1) : '--'}
                </Title>
                <Tag color="blue" style={{ marginTop: 8 }}>
                  {currentBmiCategory}
                </Tag>
              </Card>
            </Col>
            <Col xs={24} sm={12} md={12} lg={6}>
              <Card bordered={false} hoverable style={{ borderRadius: 8 }} loading={loadingCalculations}>
                <Text type="secondary" style={{ fontSize: 14 }}>
                  Last Calculation
                </Text>
                <Title level={4} style={{ margin: '8px 0 0 0' }}>
                  {lastCalculationDate ? new Date(lastCalculationDate).toLocaleDateString() : '--'}
                </Title>
                <Text type="secondary" style={{ fontSize: 12 }}>
                  Date of your most recent BMI check
                </Text>
              </Card>
            </Col>
            <Col xs={24} sm={12} md={12} lg={6}>
              <Card bordered={false} hoverable style={{ borderRadius: 8 }} loading={loadingCalculations}>
                <Text type="secondary" style={{ fontSize: 14 }}>
                  Total Calculations
                </Text>
                <Title level={2} style={{ margin: '8px 0 0 0', color: '#722ed1' }}>
                  {totalCalculations}
                </Title>
                <Text type="secondary" style={{ fontSize: 12 }}>
                  Lifetime BMI measurements
                </Text>
              </Card>
            </Col>
            <Col xs={24} sm={12} md={12} lg={6}>
              <Card bordered={false} hoverable style={{ borderRadius: 8 }} loading={loadingGoals}>
                <Text type="secondary" style={{ fontSize: 14 }}>
                  Goal Progress
                </Text>
                <Progress
                  type="circle"
                  size={80}
                  percent={goalProgress}
                  strokeColor="#52c41a"
                  style={{ marginTop: 8 }}
                />
                <Text type="secondary" style={{ fontSize: 12, marginTop: 4, display: 'block' }}>
                  Days remaining to target
                </Text>
              </Card>
            </Col>
          </Row>

          <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
            <Col xs={24} lg={16}>
              <Card bordered={false} title="BMI Trend" style={{ borderRadius: 8 }} loading={loadingCalculations}>
                <div style={{ height: 280, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>
                  {trendChartData.length > 0 ? (
                    <Text>Chart visualization: {trendChartData.length} data points</Text>
                  ) : (
                    <Text>No trend data available</Text>
                  )}
                </div>
                <Button type="link" size="small" onClick={handleViewFullHistory}>
                  View Full History →
                </Button>
              </Card>
            </Col>
            <Col xs={24} lg={8}>
              <Card bordered={false} title="Quick Calculate" style={{ borderRadius: 8, textAlign: 'center' }}>
                <Title level={1} style={{ fontSize: 64, marginBottom: 16 }}>
                  🧮
                </Title>
                <Paragraph style={{ color: '#666', marginBottom: 16 }}>
                  Calculate your BMI now with our easy-to-use calculator. Track your progress over time.
                </Paragraph>
                <Button type="primary" size="large" block onClick={handleNavigateToCalculator}>
                  Calculate BMI
                </Button>
              </Card>
            </Col>
          </Row>

          <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
            <Col xs={24}>
              <Card bordered={false} title="Active Goals" style={{ borderRadius: 8 }} loading={loadingGoals}>
                <List
                  dataSource={activeGoals}
                  locale={{ emptyText: 'No active goals. Set a goal to start tracking your progress!' }}
                  renderItem={(item: Goal) => (
                    <List.Item>
                      <List.Item.Meta
                        title={item.goal_type}
                        description={`Target: ${item.target_value} | Due: ${new Date(item.target_date).toLocaleDateString()}`}
                      />
                      <Progress
                        percent={Math.round(((item.current_value || 0) / item.target_value) * 100)}
                        status="active"
                        style={{ width: 200 }}
                      />
                    </List.Item>
                  )}
                />
                <Button type="link" size="small" onClick={handleViewAllGoals} style={{ marginTop: 16 }}>
                  View All Goals →
                </Button>
              </Card>
            </Col>
          </Row>
        </Content>
      </Layout>
    </div>
  );
};

export default DashboardPage;