import { useState, useMemo, useEffect, useCallback, CSSProperties } from 'react';
import {
  Card,
  Row,
  Col,
  Typography,
  InputNumber,
  Slider,
  Button,
  Divider,
  Statistic,
  Progress,
  message,
  Grid
} from 'antd';
import { ReloadOutlined, SaveOutlined } from '@ant-design/icons';
import { useApi } from '@/hooks/useApi';
import { SipCalculationsService } from '@/services/sipCalculations';
import { parseError } from '@/utils/errorHandler';

const { useBreakpoint } = Grid;

interface ChartDataPoint {
  year: string;
  investedAmount: number;
  projectedValue: number;
  gains: number;
}

const SipCalculatorPage = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const screens = useBreakpoint();

  const [monthlyInvestment, setMonthlyInvestment] = useState<number>(10000);
  const [expectedReturnRate, setExpectedReturnRate] = useState<number>(12);
  const [timePeriod, setTimePeriod] = useState<number>(10);
  const [calculationLoading, setCalculationLoading] = useState<boolean>(false);

  const totalMonths = useMemo(() => timePeriod * 12, [timePeriod]);
  const monthlyRate = useMemo(() => expectedReturnRate / 12 / 100, [expectedReturnRate]);
  const totalInvestment = useMemo(() => monthlyInvestment * timePeriod * 12, [monthlyInvestment, timePeriod]);
  const maturityValue = useMemo(() => {
    const r = expectedReturnRate / 12 / 100;
    const n = timePeriod * 12;
    return monthlyInvestment * (((Math.pow(1 + r, n) - 1) / r) * (1 + r));
  }, [monthlyInvestment, expectedReturnRate, timePeriod]);
  const estimatedReturns = useMemo(() => maturityValue - totalInvestment, [maturityValue, totalInvestment]);

  const chartData = useMemo<ChartDataPoint[]>(() => {
    return Array.from({ length: timePeriod }, (_, i) => {
      const year = i + 1;
      const months = year * 12;
      const r = expectedReturnRate / 12 / 100;
      const invested = monthlyInvestment * months;
      const projected = monthlyInvestment * (((Math.pow(1 + r, months) - 1) / r) * (1 + r));
      return {
        year: `Year ${year}`,
        investedAmount: Math.round(invested),
        projectedValue: Math.round(projected),
        gains: Math.round(projected - invested)
      };
    });
  }, [monthlyInvestment, expectedReturnRate, timePeriod]);

  const handleMonthlyInvestmentChange = useCallback((value: number | null) => {
    if (value !== null) {
      setMonthlyInvestment(Math.min(100000, Math.max(500, Number(value))));
    }
  }, []);

  const handleReturnRateChange = useCallback((value: number | null) => {
    if (value !== null) {
      setExpectedReturnRate(Math.min(30, Math.max(1, Number(value))));
    }
  }, []);

  const handleTimePeriodChange = useCallback((value: number | null) => {
    if (value !== null) {
      setTimePeriod(Math.min(40, Math.max(1, Math.round(Number(value)))));
    }
  }, []);

  const handleIncrementMonthlyInvestment = useCallback(() => {
    setMonthlyInvestment(prev => Math.min(100000, prev + 500));
  }, []);

  const handleDecrementMonthlyInvestment = useCallback(() => {
    setMonthlyInvestment(prev => Math.max(500, prev - 500));
  }, []);

  const handleIncrementReturnRate = useCallback(() => {
    setExpectedReturnRate(prev => Math.min(30, prev + 0.5));
  }, []);

  const handleDecrementReturnRate = useCallback(() => {
    setExpectedReturnRate(prev => Math.max(1, prev - 0.5));
  }, []);

  const handleIncrementTimePeriod = useCallback(() => {
    setTimePeriod(prev => Math.min(40, prev + 1));
  }, []);

  const handleDecrementTimePeriod = useCallback(() => {
    setTimePeriod(prev => Math.max(1, prev - 1));
  }, []);

  const handleResetDefaults = useCallback(() => {
    setMonthlyInvestment(10000);
    setExpectedReturnRate(12);
    setTimePeriod(10);
    messageApi.info('All inputs reset to defaults');
  }, [messageApi]);

  const handleSaveCalculation = useCallback(async () => {
    if (monthlyInvestment < 500) {
      messageApi.error('Monthly investment must be at least ₹500');
      return;
    }
    if (monthlyInvestment > 100000) {
      messageApi.error('Monthly investment cannot exceed ₹1,00,000');
      return;
    }
    if (expectedReturnRate < 1) {
      messageApi.error('Return rate must be at least 1%');
      return;
    }
    if (expectedReturnRate > 30) {
      messageApi.error('Return rate cannot exceed 30%');
      return;
    }
    if (timePeriod < 1) {
      messageApi.error('Time period must be at least 1 year');
      return;
    }
    if (timePeriod > 40) {
      messageApi.error('Time period cannot exceed 40 years');
      return;
    }

    setCalculationLoading(true);
    try {
      await SipCalculationsService.create({
        monthly_investment: monthlyInvestment,
        expected_return_rate: expectedReturnRate,
        time_period: timePeriod
      });
      messageApi.success('Calculation saved successfully!');
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage);
    } finally {
      setCalculationLoading(false);
    }
  }, [monthlyInvestment, expectedReturnRate, timePeriod, messageApi]);

  const formatIndianCurrency = useCallback((value: number): string => {
    return new Intl.NumberFormat('en-IN', {
      style: 'currency',
      currency: 'INR',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0
    }).format(value);
  }, []);

  const investedPercentage = useMemo(() => {
    return Math.round((totalInvestment / maturityValue) * 100);
  }, [totalInvestment, maturityValue]);

  const contentPadding = screens.xs ? 12 : 24;
  const titleFontSize = screens.xs ? '24px' : '32px';

  return (
    <div style={{ minHeight: '100vh', width: '100%', background: '#f5f5f5', padding: 0 }} aria-label="SIP Calculator Application">
      {contextHolder}
      <div style={{ background: 'linear-gradient(135deg, #1677ff 0%, #0958d9 100%)', padding: `${contentPadding}px`, textAlign: 'center' }}>
        <Typography.Title level={1} style={{ color: '#ffffff', margin: 0, fontSize: titleFontSize, fontWeight: '700' }} aria-label="SIP Calculator">
          SIP Calculator
        </Typography.Title>
        <Typography.Text style={{ color: 'rgba(255,255,255,0.85)', fontSize: screens.xs ? '14px' : '16px', display: 'block', marginTop: '8px' }}>
          Plan your Systematic Investment and watch your wealth grow
        </Typography.Text>
      </div>

      <div style={{ maxWidth: '1200px', margin: '0 auto', padding: `${contentPadding}px`, width: '100%' }}>
        <Row gutter={[24, 24]}>
          <Col xs={24} lg={12}>
            <Card
              title="Investment Parameters"
              aria-label="Investment input parameters section"
              style={{ borderRadius: '8px', boxShadow: '0 2px 8px rgba(0,0,0,0.06)', height: '100%' }}
            >
              <div style={{ marginBottom: '28px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
                  <Typography.Text strong style={{ fontSize: '14px', color: '#434343' }}>
                    Monthly Investment
                  </Typography.Text>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <Button
                      shape="circle"
                      size="middle"
                      aria-label="Decrease monthly investment by ₹500"
                      style={{ minWidth: '36px', minHeight: '36px' }}
                      onClick={handleDecrementMonthlyInvestment}
                    >
                      −
                    </Button>
                    <InputNumber
                      min={500}
                      max={100000}
                      step={500}
                      prefix="₹"
                      formatter={(value) => `${value}`.replace(/\B(?=(\d{2})+(?=\d{3})(?!\d))/g, ',')}
                      parser={(value) => (value ?? '').replace(/₹\s?|(,*)/g, '')}
                      aria-label="Monthly investment amount in rupees"
                      controls={false}
                      style={{ width: '160px', textAlign: 'right' }}
                      value={monthlyInvestment}
                      onChange={handleMonthlyInvestmentChange}
                    />
                    <Button
                      shape="circle"
                      size="middle"
                      aria-label="Increase monthly investment by ₹500"
                      style={{ minWidth: '36px', minHeight: '36px' }}
                      onClick={handleIncrementMonthlyInvestment}
                    >
                      +
                    </Button>
                  </div>
                </div>
                <Slider
                  min={500}
                  max={100000}
                  step={500}
                  aria-label="Monthly investment slider"
                  value={monthlyInvestment}
                  onChange={handleMonthlyInvestmentChange}
                />
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '-4px' }}>
                  <Typography.Text type="secondary" style={{ fontSize: '12px' }}>
                    ₹500
                  </Typography.Text>
                  <Typography.Text type="secondary" style={{ fontSize: '12px' }}>
                    ₹1,00,000
                  </Typography.Text>
                </div>
              </div>

              <div style={{ marginBottom: '28px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
                  <Typography.Text strong style={{ fontSize: '14px', color: '#434343' }}>
                    Expected Return Rate (p.a.)
                  </Typography.Text>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <Button
                      shape="circle"
                      size="middle"
                      aria-label="Decrease return rate by 0.5%"
                      style={{ minWidth: '36px', minHeight: '36px' }}
                      onClick={handleDecrementReturnRate}
                    >
                      −
                    </Button>
                    <InputNumber
                      min={1}
                      max={30}
                      step={0.5}
                      suffix="%"
                      precision={2}
                      aria-label="Expected annual return rate percentage"
                      controls={false}
                      style={{ width: '120px', textAlign: 'right' }}
                      value={expectedReturnRate}
                      onChange={handleReturnRateChange}
                    />
                    <Button
                      shape="circle"
                      size="middle"
                      aria-label="Increase return rate by 0.5%"
                      style={{ minWidth: '36px', minHeight: '36px' }}
                      onClick={handleIncrementReturnRate}
                    >
                      +
                    </Button>
                  </div>
                </div>
                <Slider
                  min={1}
                  max={30}
                  step={0.5}
                  aria-label="Return rate slider"
                  value={expectedReturnRate}
                  onChange={handleReturnRateChange}
                />
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '-4px' }}>
                  <Typography.Text type="secondary" style={{ fontSize: '12px' }}>
                    1%
                  </Typography.Text>
                  <Typography.Text type="secondary" style={{ fontSize: '12px' }}>
                    30%
                  </Typography.Text>
                </div>
              </div>

              <div style={{ marginBottom: '24px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
                  <Typography.Text strong style={{ fontSize: '14px', color: '#434343' }}>
                    Time Period
                  </Typography.Text>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <Button
                      shape="circle"
                      size="middle"
                      aria-label="Decrease time period by 1 year"
                      style={{ minWidth: '36px', minHeight: '36px' }}
                      onClick={handleDecrementTimePeriod}
                    >
                      −
                    </Button>
                    <InputNumber
                      min={1}
                      max={40}
                      step={1}
                      suffix="Yrs"
                      precision={0}
                      aria-label="Investment time period in years"
                      controls={false}
                      style={{ width: '120px', textAlign: 'right' }}
                      value={timePeriod}
                      onChange={handleTimePeriodChange}
                    />
                    <Button
                      shape="circle"
                      size="middle"
                      aria-label="Increase time period by 1 year"
                      style={{ minWidth: '36px', minHeight: '36px' }}
                      onClick={handleIncrementTimePeriod}
                    >
                      +
                    </Button>
                  </div>
                </div>
                <Slider
                  min={1}
                  max={40}
                  step={1}
                  aria-label="Time period slider"
                  value={timePeriod}
                  onChange={handleTimePeriodChange}
                />
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '-4px' }}>
                  <Typography.Text type="secondary" style={{ fontSize: '12px' }}>
                    1 Yr
                  </Typography.Text>
                  <Typography.Text type="secondary" style={{ fontSize: '12px' }}>
                    40 Yrs
                  </Typography.Text>
                </div>
              </div>

              <div style={{ display: 'flex', gap: '12px', justifyContent: screens.xs ? 'stretch' : 'flex-end', marginTop: '8px', flexDirection: screens.xs ? 'column' : 'row' }}>
                <Button
                  icon={<ReloadOutlined />}
                  aria-label="Reset all inputs to default values"
                  style={{ minHeight: '44px' }}
                  onClick={handleResetDefaults}
                >
                  Reset to Defaults
                </Button>
                <Button
                  type="primary"
                  icon={<SaveOutlined />}
                  loading={calculationLoading}
                  aria-label="Save this calculation to server"
                  style={{ minHeight: '44px' }}
                  onClick={handleSaveCalculation}
                >
                  Save Calculation
                </Button>
              </div>
            </Card>
          </Col>

          <Col xs={24} lg={12}>
            <Card
              title="Investment Summary"
              aria-label="Calculation results section"
              style={{ borderRadius: '8px', boxShadow: '0 2px 8px rgba(0,0,0,0.06)', height: '100%' }}
            >
              <Row gutter={[16, 16]}>
                <Col xs={24} sm={24}>
                  <Card
                    size="small"
                    aria-label="Total investment amount"
                    style={{ background: '#f0f5ff', border: '1px solid #d6e4ff', borderRadius: '8px' }}
                  >
                    <Typography.Text type="secondary" style={{ fontSize: '13px', display: 'block', marginBottom: '4px' }}>
                      Total Investment
                    </Typography.Text>
                    <Statistic
                      prefix="₹"
                      precision={0}
                      groupSeparator=","
                      valueStyle={{ fontSize: '24px', fontWeight: '600', color: '#1677ff' }}
                      value={totalInvestment}
                      aria-label="Total amount you will invest"
                    />
                  </Card>
                </Col>

                <Col xs={24} sm={24}>
                  <Card
                    size="small"
                    aria-label="Estimated returns amount"
                    style={{ background: '#f6ffed', border: '1px solid #d9f7be', borderRadius: '8px' }}
                  >
                    <Typography.Text type="secondary" style={{ fontSize: '13px', display: 'block', marginBottom: '4px' }}>
                      Estimated Returns
                    </Typography.Text>
                    <Statistic
                      prefix="₹"
                      precision={0}
                      groupSeparator=","
                      valueStyle={{ fontSize: '24px', fontWeight: '600', color: '#52c41a' }}
                      value={estimatedReturns}
                      aria-label="Estimated wealth gained"
                    />
                  </Card>
                </Col>

                <Col xs={24} sm={24}>
                  <Card
                    size="small"
                    aria-label="Total maturity value"
                    style={{ background: 'linear-gradient(135deg, #1677ff 0%, #0958d9 100%)', border: 'none', borderRadius: '8px' }}
                  >
                    <Typography.Text style={{ fontSize: '13px', display: 'block', marginBottom: '4px', color: 'rgba(255,255,255,0.85)' }}>
                      Maturity Value
                    </Typography.Text>
                    <Statistic
                      prefix="₹"
                      precision={0}
                      groupSeparator=","
                      valueStyle={{ fontSize: '32px', fontWeight: '700', color: '#ffffff' }}
                      value={maturityValue}
                      aria-label="Total maturity value of your SIP investment"
                    />
                  </Card>
                </Col>
              </Row>

              <Divider dashed style={{ margin: '16px 0' }} />

              <Typography.Text strong type="secondary" style={{ fontSize: '13px', display: 'block', marginBottom: '12px' }}>
                Investment Breakdown
              </Typography.Text>

              <Progress
                percent={investedPercentage}
                strokeColor="#1677ff"
                trailColor="#52c41a"
                showInfo={true}
                format={() => `Invested: ${investedPercentage}%`}
                aria-label="Percentage of maturity that is invested amount"
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={[24, 24]} style={{ marginTop: '24px' }}>
          <Col xs={24}>
            <Card
              title="Investment Growth Over Time"
              aria-label="Chart showing investment growth projection over time"
              style={{ borderRadius: '8px', boxShadow: '0 2px 8px rgba(0,0,0,0.06)' }}
            >
              <div style={{ width: '100%', overflowX: 'auto' }}>
                <div style={{ minWidth: screens.xs ? '600px' : '100%' }}>
                  <div style={{ padding: '20px 0' }}>
                    {chartData.map((point, index) => (
                      <div key={index} style={{ marginBottom: '16px' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                          <Typography.Text strong>{point.year}</Typography.Text>
                          <Typography.Text type="secondary">
                            Invested: {formatIndianCurrency(point.investedAmount)} | Projected: {formatIndianCurrency(point.projectedValue)}
                          </Typography.Text>
                        </div>
                        <div style={{ display: 'flex', gap: '2px', height: '40px' }}>
                          <div
                            style={{
                              flex: point.investedAmount,
                              background: '#1677ff',
                              borderRadius: '4px',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              color: '#fff',
                              fontSize: '12px',
                              fontWeight: '500'
                            }}
                          >
                            {point.investedAmount > maturityValue * 0.1 ? formatIndianCurrency(point.investedAmount) : ''}
                          </div>
                          <div
                            style={{
                              flex: point.gains,
                              background: '#52c41a',
                              borderRadius: '4px',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              color: '#fff',
                              fontSize: '12px',
                              fontWeight: '500'
                            }}
                          >
                            {point.gains > maturityValue * 0.1 ? `+${formatIndianCurrency(point.gains)}` : ''}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                  <div style={{ display: 'flex', gap: '16px', justifyContent: 'center', marginTop: '16px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <div style={{ width: '16px', height: '16px', background: '#1677ff', borderRadius: '2px' }} />
                      <Typography.Text>Total Invested</Typography.Text>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <div style={{ width: '16px', height: '16px', background: '#52c41a', borderRadius: '2px' }} />
                      <Typography.Text>Projected Gains</Typography.Text>
                    </div>
                  </div>
                </div>
              </div>
            </Card>
          </Col>
        </Row>
      </div>

      <div style={{ textAlign: 'center', padding: `${contentPadding}px`, marginTop: '16px' }}>
        <Typography.Text type="secondary" style={{ fontSize: '12px' }}>
          Disclaimer: This calculator provides estimates based on projected returns. Actual returns may vary. Mutual fund investments are subject to market risks.
        </Typography.Text>
        <Typography.Text type="secondary" style={{ fontSize: '11px', display: 'block', marginTop: '4px' }}>
          Formula: M = P × ({'{'}[1 + i]ⁿ – 1{'}'} / i) × (1 + i) where P = Monthly Investment, i = Monthly Rate, n = Total Months
        </Typography.Text>
      </div>
    </div>
  );
};

export default SipCalculatorPage;