import { useState, useMemo, CSSProperties } from 'react';
import { Form, InputNumber, Select, Button, Card, Row, Col, Statistic, Typography, Tooltip, Space, message } from 'antd';
import { InfoCircleOutlined } from '@ant-design/icons';
import { SipCalculationService } from '@/services/sipCalculation';
import { parseError } from '@/utils/errorHandler';

type PeriodUnit = 'MONTHS' | 'YEARS';

interface ChartDataPoint {
  period: number;
  invested_amount: number;
  projected_value: number;
}

interface CalculationResult {
  calculation_result_id: string;
  total_investment: number;
  estimated_returns: number;
  future_value: number;
  chart_data_points: ChartDataPoint[];
}

interface ComputeSIPRequest {
  monthly_investment?: number;
  annual_return_rate?: number;
  investment_period?: number;
  period_unit: PeriodUnit;
}

const SipCalculatorPage = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();

  const [calculationResult, setCalculationResult] = useState<CalculationResult>({
    calculation_result_id: '',
    total_investment: 0,
    estimated_returns: 0,
    future_value: 0,
    chart_data_points: [],
  });
  const [isCalculating, setIsCalculating] = useState<boolean>(false);
  const [hasCalculated, setHasCalculated] = useState<boolean>(false);

  const roiPercentage = useMemo(() => {
    return calculationResult.total_investment > 0
      ? ((calculationResult.estimated_returns / calculationResult.total_investment) * 100).toFixed(2)
      : '0';
  }, [calculationResult.total_investment, calculationResult.estimated_returns]);

  const investmentProportion = useMemo(() => {
    return calculationResult.future_value > 0
      ? ((calculationResult.total_investment / calculationResult.future_value) * 100).toFixed(1)
      : '0';
  }, [calculationResult.total_investment, calculationResult.future_value]);

  const returnsProportion = useMemo(() => {
    return calculationResult.future_value > 0
      ? ((calculationResult.estimated_returns / calculationResult.future_value) * 100).toFixed(1)
      : '0';
  }, [calculationResult.estimated_returns, calculationResult.future_value]);

  const handleCalculateSIP = async () => {
    try {
      const values = await form.validateFields();
      setIsCalculating(true);

      const payload: ComputeSIPRequest = {
        monthly_investment: values.monthly_investment,
        annual_return_rate: values.annual_return_rate,
        investment_period: values.investment_period,
        period_unit: values.period_unit,
      };

      const response = await SipCalculationService.computeSIP(payload);
      setCalculationResult(response.data);
      setIsCalculating(false);
      setHasCalculated(true);
      messageApi.success('Calculation complete');
    } catch (e) {
      setIsCalculating(false);
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage || 'Calculation failed. Please check your inputs.');
    }
  };

  const handleResetCalculator = async () => {
    try {
      setHasCalculated(false);
      const response = await SipCalculationService.resetCalculator();
      setCalculationResult(response.data);
      form.setFieldsValue({
        monthly_investment: 500,
        annual_return_rate: 12,
        investment_period: 10,
        period_unit: 'YEARS',
      });
      messageApi.info('Calculator reset to default values');
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage || 'Failed to reset calculator');
    }
  };

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

  const pageHeaderStyle: CSSProperties = {
    textAlign: 'center',
    marginBottom: '24px',
  };

  const pageTitleStyle: CSSProperties = {
    marginBottom: '4px',
  };

  const infoTooltipStyle: CSSProperties = {
    marginLeft: '8px',
  };

  const infoIconStyle: CSSProperties = {
    color: '#1677ff',
    fontSize: '16px',
  };

  const formActionsStyle: CSSProperties = {
    display: 'flex',
    gap: '12px',
    marginTop: '16px',
  };

  const calculateButtonStyle: CSSProperties = {
    flex: 1,
  };

  const resetButtonStyle: CSSProperties = {
    flex: 1,
  };

  const resultsSectionStyle: CSSProperties = {
    display: 'flex',
    flexDirection: 'column',
    gap: '16px',
  };

  const totalInvestmentCardStyle: CSSProperties = {
    borderTop: '3px solid #1677ff',
  };

  const estimatedReturnsCardStyle: CSSProperties = {
    borderTop: '3px solid #52c41a',
  };

  const futureValueCardStyle: CSSProperties = {
    borderTop: '3px solid #722ed1',
    boxShadow: '0 2px 8px rgba(114, 46, 209, 0.15)',
  };

  const breakdownContentStyle: CSSProperties = {
    display: 'flex',
    justifyContent: 'space-around',
    alignItems: 'center',
  };

  const investmentProportionStyle: CSSProperties = {
    color: '#1677ff',
  };

  const returnsProportionStyle: CSSProperties = {
    color: '#52c41a',
  };

  const roiStyle: CSSProperties = {
    color: '#722ed1',
  };

  return (
    <div style={mainContainerStyle}>
      {contextHolder}
      <div style={pageHeaderStyle}>
        <Typography.Title level={2} style={pageTitleStyle}>
          SIP Calculator
        </Typography.Title>
        <Typography.Text type="secondary">
          Calculate the future value of your Systematic Investment Plan
        </Typography.Text>
        <Tooltip
          title="SIP (Systematic Investment Plan) allows you to invest a fixed amount regularly. Formula: FV = P × ({[1 + i]^n – 1} / i) × (1 + i), where P = monthly investment, i = monthly rate of return, n = number of months"
          style={infoTooltipStyle}
        >
          <InfoCircleOutlined style={infoIconStyle} />
        </Tooltip>
      </div>

      <Row gutter={[24, 24]}>
        <Col xs={24} md={10} lg={8}>
          <Card title="Investment Parameters" style={{ height: '100%' }}>
            <Form
              form={form}
              layout="vertical"
              onFinish={handleCalculateSIP}
              initialValues={{
                monthly_investment: 500,
                annual_return_rate: 12,
                investment_period: 10,
                period_unit: 'YEARS',
              }}
            >
              <Form.Item
                name="monthly_investment"
                label="Monthly Investment ($)"
                tooltip="Amount you plan to invest every month"
                rules={[
                  { required: true, message: 'Please enter monthly investment' },
                  { type: 'number', min: 1, max: 10000000, message: 'Value must be between $1 and $10,000,000' },
                ]}
              >
                <InputNumber
                  prefix="$"
                  min={1}
                  max={10000000}
                  precision={2}
                  style={{ width: '100%' }}
                  placeholder="Enter monthly investment"
                  aria-label="Monthly Investment input"
                />
              </Form.Item>

              <Form.Item
                name="annual_return_rate"
                label="Annual Return Rate (%)"
                tooltip="Expected annual rate of return on your investment"
                rules={[
                  { required: true, message: 'Please enter annual return rate' },
                  { type: 'number', min: 0.1, max: 50, message: 'Value must be between 0.1% and 50%' },
                ]}
              >
                <InputNumber
                  suffix="%"
                  min={0.1}
                  max={50}
                  precision={2}
                  style={{ width: '100%' }}
                  placeholder="Enter annual return rate"
                  aria-label="Annual Return Rate input"
                />
              </Form.Item>

              <Form.Item
                name="investment_period"
                label="Investment Period"
                tooltip="Duration of your investment"
                rules={[
                  { required: true, message: 'Please enter investment period' },
                  { type: 'number', min: 1, max: 480, message: 'Value must be between 1 and 40 years (480 months)' },
                ]}
              >
                <Space.Compact style={{ width: '100%' }}>
                  <InputNumber
                    min={1}
                    max={480}
                    precision={0}
                    style={{ width: '70%' }}
                    placeholder="Enter period"
                    aria-label="Investment Period input"
                  />
                  <Form.Item name="period_unit" noStyle>
                    <Select
                      options={[
                        { label: 'Years', value: 'YEARS' },
                        { label: 'Months', value: 'MONTHS' },
                      ]}
                      style={{ width: '30%' }}
                      aria-label="Period Unit selector"
                    />
                  </Form.Item>
                </Space.Compact>
              </Form.Item>

              <div style={formActionsStyle}>
                <Button
                  type="primary"
                  htmlType="submit"
                  size="large"
                  loading={isCalculating}
                  style={calculateButtonStyle}
                  aria-label="Calculate button"
                >
                  Calculate
                </Button>
                <Button
                  size="large"
                  onClick={handleResetCalculator}
                  style={resetButtonStyle}
                  aria-label="Reset button"
                >
                  Reset
                </Button>
              </div>
            </Form>
          </Card>
        </Col>

        <Col xs={24} md={14} lg={16}>
          <div style={resultsSectionStyle}>
            <Row gutter={[16, 16]}>
              <Col xs={24} sm={8}>
                <Card size="small" style={totalInvestmentCardStyle}>
                  <Statistic
                    title="Total Investment"
                    value={calculationResult.total_investment}
                    prefix="$"
                    precision={2}
                    valueStyle={{ color: '#1677ff' }}
                    aria-label="Total Investment result"
                  />
                </Card>
              </Col>

              <Col xs={24} sm={8}>
                <Card size="small" style={estimatedReturnsCardStyle}>
                  <Statistic
                    title="Estimated Returns"
                    value={calculationResult.estimated_returns}
                    prefix="$"
                    precision={2}
                    valueStyle={{ color: '#52c41a' }}
                    aria-label="Estimated Returns result"
                  />
                </Card>
              </Col>

              <Col xs={24} sm={8}>
                <Card size="small" style={futureValueCardStyle}>
                  <Statistic
                    title="Future Value (Maturity)"
                    value={calculationResult.future_value}
                    prefix="$"
                    precision={2}
                    valueStyle={{ color: '#722ed1', fontWeight: 'bold' }}
                    aria-label="Future Value result"
                  />
                </Card>
              </Col>
            </Row>

            <Card title="Investment Breakdown" size="small">
              <div style={breakdownContentStyle}>
                <div>
                  <Typography.Text type="secondary">Investment</Typography.Text>
                  <br />
                  <Typography.Text strong style={investmentProportionStyle}>
                    {investmentProportion}%
                  </Typography.Text>
                </div>
                <div>
                  <Typography.Text type="secondary">Returns</Typography.Text>
                  <br />
                  <Typography.Text strong style={returnsProportionStyle}>
                    {returnsProportion}%
                  </Typography.Text>
                </div>
                <div>
                  <Typography.Text type="secondary">ROI</Typography.Text>
                  <br />
                  <Typography.Text strong style={roiStyle}>
                    {roiPercentage}%
                  </Typography.Text>
                </div>
              </div>
            </Card>

            <Row gutter={[16, 16]}>
              <Col xs={24} lg={14}>
                <Card title="Investment Growth Over Time" size="small" style={{ height: '100%' }}>
                  <div style={{ height: 280, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Typography.Text type="secondary">Chart visualization placeholder</Typography.Text>
                  </div>
                </Card>
              </Col>

              <Col xs={24} lg={10}>
                <Card title="Investment Composition" size="small" style={{ height: '100%' }}>
                  <div style={{ height: 280, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Typography.Text type="secondary">Chart visualization placeholder</Typography.Text>
                  </div>
                </Card>
              </Col>
            </Row>
          </div>
        </Col>
      </Row>
    </div>
  );
};

export default SipCalculatorPage;