import { useState, useMemo, useEffect, CSSProperties } from 'react';
import { Form, InputNumber, Select, Button, Card, Row, Col, Statistic, Table, Space, Typography, Empty, message, Grid } from 'antd';
import { CalculatorOutlined, ClearOutlined, DownloadOutlined, PrinterOutlined } from '@ant-design/icons';
import { LoanCalculationsService } from '@/services/loanCalculations';
import { useApi } from '@/hooks/useApi';
import { parseError } from '@/utils/errorHandler';

interface CalculationResult {
  id: string;
  principal: number;
  annual_interest_rate: number;
  loan_term_months: number;
  monthly_payment: number;
  total_interest: number;
  total_amount_paid: number;
  calculation_method: string;
  start_date: string | null;
  created_at: string;
  updated_at: string;
}

interface AmortizationEntry {
  payment_number: number;
  payment_date: string;
  beginning_balance: number;
  payment_amount: number;
  principal_payment: number;
  interest_payment: number;
  ending_balance: number;
  cumulative_interest: number;
}

interface CalculationDetailResponse {
  id: string;
  principal: number;
  annual_interest_rate: number;
  loan_term_months: number;
  monthly_payment: number;
  total_interest: number;
  total_amount_paid: number;
  calculation_method: string;
  start_date: string | null;
  created_at: string;
  updated_at: string;
  amortization_schedule_entries: AmortizationEntry[];
}

const LoanCalculatorPage = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();
  const { useBreakpoint } = Grid;
  const screens = useBreakpoint();

  const [termUnit, setTermUnit] = useState<'months' | 'years'>('months');
  const [calculationResult, setCalculationResult] = useState<CalculationResult | null>(null);
  const [amortizationSchedule, setAmortizationSchedule] = useState<AmortizationEntry[]>([]);
  const [isCalculating, setIsCalculating] = useState(false);
  const [hasCalculated, setHasCalculated] = useState(false);
  const [calculationId, setCalculationId] = useState('');

  const { data: detailData, execute: fetchDetails } = useApi<CalculationDetailResponse>(
    LoanCalculationsService.getDetails
  );

  const loanTermDisplay = useMemo(() => {
    if (!calculationResult) return '';
    return `${calculationResult.loan_term_months} months (${(calculationResult.loan_term_months / 12).toFixed(1)} years)`;
  }, [calculationResult]);

  const showResults = useMemo(() => {
    return hasCalculated && calculationResult !== null;
  }, [hasCalculated, calculationResult]);

  useEffect(() => {
    if (detailData?.amortization_schedule_entries) {
      setAmortizationSchedule(detailData.amortization_schedule_entries);
      setHasCalculated(true);
      setIsCalculating(false);
    }
  }, [detailData]);

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

      const loanTermMonths = termUnit === 'years' ? values.loan_term * 12 : values.loan_term;

      const response = await LoanCalculationsService.create({
        principal: values.principal,
        annual_interest_rate: values.annual_interest_rate,
        loan_term_months: loanTermMonths,
        calculation_method: 'standard_amortization',
        start_date: null
      });

      setCalculationResult(response.data as CalculationResult);
      setCalculationId(response.data.id);
      messageApi.success('Loan calculated successfully!');

      await fetchDetails(response.data.id);
    } catch (e) {
      const { message: errorMsg } = parseError(e);
      messageApi.error(errorMsg || 'Failed to calculate loan. Please check your inputs and try again.');
      setIsCalculating(false);
    }
  };

  const handleReset = () => {
    form.resetFields();
    setCalculationResult(null);
    setAmortizationSchedule([]);
    setHasCalculated(false);
    setIsCalculating(false);
    setCalculationId('');
    setTermUnit('months');
    messageApi.info('Form has been reset');
  };

  const handleExportCsv = () => {
    try {
      if (!amortizationSchedule || amortizationSchedule.length === 0) {
        messageApi.error('No data to export');
        return;
      }

      const headers = [
        'Payment #',
        'Payment Date',
        'Beginning Balance',
        'Payment Amount',
        'Principal',
        'Interest',
        'Ending Balance',
        'Cumulative Interest'
      ];

      const csvRows = [
        headers.join(','),
        ...amortizationSchedule.map(entry =>
          [
            entry.payment_number,
            entry.payment_date,
            entry.beginning_balance.toFixed(2),
            entry.payment_amount.toFixed(2),
            entry.principal_payment.toFixed(2),
            entry.interest_payment.toFixed(2),
            entry.ending_balance.toFixed(2),
            entry.cumulative_interest.toFixed(2)
          ].join(',')
        )
      ];

      const csvContent = csvRows.join('\n');
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      const filename = `loan_schedule_${new Date().toISOString().slice(0, 10).replace(/-/g, '')}.csv`;
      link.setAttribute('href', url);
      link.setAttribute('download', filename);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      messageApi.success('CSV exported successfully');
    } catch (e) {
      messageApi.error('Failed to export CSV');
    }
  };

  const handlePrint = () => {
    window.print();
  };

  const formatCurrency = (value: number) => {
    return `$${value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
  };

  const formatDate = (dateStr: string) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return date.toLocaleDateString('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' });
  };

  const tableColumns = useMemo(
    () => [
      {
        title: 'Payment #',
        dataIndex: 'payment_number',
        key: 'payment_number',
        width: 90,
        align: 'left' as const,
        fixed: 'left' as const
      },
      {
        title: 'Payment Date',
        dataIndex: 'payment_date',
        key: 'payment_date',
        width: 120,
        align: 'left' as const,
        render: (date: string) => formatDate(date)
      },
      {
        title: 'Beginning Balance',
        dataIndex: 'beginning_balance',
        key: 'beginning_balance',
        width: 150,
        align: 'right' as const,
        render: (val: number) => formatCurrency(val)
      },
      {
        title: 'Payment Amount',
        dataIndex: 'payment_amount',
        key: 'payment_amount',
        width: 140,
        align: 'right' as const,
        render: (val: number) => formatCurrency(val)
      },
      {
        title: 'Principal',
        dataIndex: 'principal_payment',
        key: 'principal_payment',
        width: 130,
        align: 'right' as const,
        render: (val: number) => formatCurrency(val)
      },
      {
        title: 'Interest',
        dataIndex: 'interest_payment',
        key: 'interest_payment',
        width: 130,
        align: 'right' as const,
        render: (val: number) => formatCurrency(val)
      },
      {
        title: 'Ending Balance',
        dataIndex: 'ending_balance',
        key: 'ending_balance',
        width: 150,
        align: 'right' as const,
        render: (val: number) => formatCurrency(val)
      },
      {
        title: 'Cumulative Interest',
        dataIndex: 'cumulative_interest',
        key: 'cumulative_interest',
        width: 160,
        align: 'right' as const,
        render: (val: number) => formatCurrency(val)
      }
    ],
    []
  );

  const containerPadding = screens.xs ? 12 : 24;
  const headerFontSize = screens.xs ? '24px' : '32px';
  const subtitleFontSize = screens.xs ? '14px' : '16px';

  return (
    <div style={{ minHeight: '100vh', width: '100%', backgroundColor: '#f5f5f5', padding: 0 }}>
      {contextHolder}
      <div
        style={{
          background: 'linear-gradient(135deg, #1677ff 0%, #0958d9 100%)',
          padding: '32px 24px',
          textAlign: 'center'
        }}
      >
        <Typography.Title
          level={1}
          style={{ color: '#ffffff', margin: 0, fontSize: headerFontSize, fontWeight: 700 }}
        >
          Loan Calculator
        </Typography.Title>
        <Typography.Text
          style={{
            color: 'rgba(255,255,255,0.85)',
            fontSize: subtitleFontSize,
            display: 'block',
            marginTop: '8px'
          }}
        >
          Calculate your monthly payments, total interest, and view a detailed amortization schedule
        </Typography.Text>
      </div>

      <div style={{ maxWidth: '1200px', margin: '0 auto', padding: containerPadding, width: '100%' }}>
        <Card
          title="Loan Details"
          bordered={false}
          style={{ marginBottom: '24px', boxShadow: '0 2px 8px rgba(0,0,0,0.08)', borderRadius: '8px' }}
        >
          <Form form={form} layout="vertical" name="loan_calculator_form" onFinish={handleCalculate}>
            <Row gutter={[24, 16]}>
              <Col xs={24} sm={24} md={8}>
                <Form.Item
                  label="Loan Amount"
                  name="principal"
                  rules={[
                    { required: true, message: 'Loan amount is required' },
                    {
                      type: 'number',
                      min: 1,
                      max: 100000000,
                      message: 'Must be between $1 and $100,000,000',
                      transform: (value) => Number(value)
                    }
                  ]}
                >
                  <InputNumber
                    placeholder="250,000"
                    prefix="$"
                    min={1}
                    max={100000000}
                    precision={2}
                    formatter={(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                    parser={(value) => (value ?? '').replace(/\$\s?|(,*)/g, '')}
                    style={{ width: '100%' }}
                    size="large"
                  />
                </Form.Item>
              </Col>

              <Col xs={24} sm={24} md={8}>
                <Form.Item
                  label="Annual Interest Rate"
                  name="annual_interest_rate"
                  rules={[
                    { required: true, message: 'Interest rate is required' },
                    {
                      type: 'number',
                      min: 0,
                      max: 30,
                      message: 'Must be between 0% and 30%',
                      transform: (value) => Number(value)
                    }
                  ]}
                >
                  <InputNumber
                    placeholder="4.5"
                    suffix="%"
                    min={0}
                    max={30}
                    precision={3}
                    step={0.125}
                    style={{ width: '100%' }}
                    size="large"
                  />
                </Form.Item>
              </Col>

              <Col xs={24} sm={24} md={8}>
                <Form.Item
                  label="Loan Term"
                  name="loan_term"
                  rules={[
                    { required: true, message: 'Loan term is required' },
                    {
                      type: 'integer',
                      min: 1,
                      message: 'Must be at least 1',
                      transform: (value) => Number(value)
                    }
                  ]}
                >
                  <Space.Compact style={{ width: '100%' }}>
                    <InputNumber
                      placeholder="360"
                      min={1}
                      max={360}
                      precision={0}
                      style={{ width: '70%' }}
                      size="large"
                    />
                    <Select
                      value={termUnit}
                      onChange={setTermUnit}
                      style={{ width: '30%' }}
                      size="large"
                      options={[
                        { value: 'months', label: 'Months' },
                        { value: 'years', label: 'Years' }
                      ]}
                    />
                  </Space.Compact>
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16} style={{ marginTop: '16px' }}>
              <Col>
                <Button
                  type="primary"
                  htmlType="submit"
                  size="large"
                  icon={<CalculatorOutlined />}
                  loading={isCalculating}
                  style={{ minWidth: '160px', height: '44px', fontWeight: 600 }}
                >
                  Calculate
                </Button>
              </Col>
              <Col>
                <Button
                  size="large"
                  icon={<ClearOutlined />}
                  onClick={handleReset}
                  style={{ minWidth: '120px', height: '44px' }}
                >
                  Reset
                </Button>
              </Col>
            </Row>
          </Form>
        </Card>

        {showResults && (
          <div style={{ marginBottom: '24px' }}>
            <Card
              title="Calculation Results"
              bordered={false}
              style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)', borderRadius: '8px' }}
            >
              <Row gutter={[24, 24]}>
                <Col xs={24} sm={12} md={8}>
                  <Statistic
                    title="Monthly Payment"
                    value={calculationResult?.monthly_payment ?? 0}
                    prefix="$"
                    precision={2}
                    valueStyle={{ color: '#1677ff', fontSize: '32px', fontWeight: 700 }}
                  />
                </Col>
                <Col xs={24} sm={12} md={8}>
                  <Statistic
                    title="Total Interest Paid"
                    value={calculationResult?.total_interest ?? 0}
                    prefix="$"
                    precision={2}
                    valueStyle={{ color: '#faad14', fontSize: '24px', fontWeight: 600 }}
                  />
                </Col>
                <Col xs={24} sm={12} md={8}>
                  <Statistic
                    title="Total Amount Paid"
                    value={calculationResult?.total_amount_paid ?? 0}
                    prefix="$"
                    precision={2}
                    valueStyle={{ fontSize: '24px', fontWeight: 600 }}
                  />
                </Col>
                <Col xs={24} sm={12} md={12}>
                  <Statistic
                    title="Loan Term"
                    value={loanTermDisplay}
                    valueStyle={{ fontSize: '18px' }}
                  />
                </Col>
                <Col xs={24} sm={12} md={12}>
                  <Statistic
                    title="Interest Rate"
                    value={calculationResult?.annual_interest_rate ?? 0}
                    suffix="%"
                    precision={3}
                    valueStyle={{ fontSize: '18px' }}
                  />
                </Col>
              </Row>
            </Card>
          </div>
        )}

        {showResults && (
          <div style={{ marginBottom: '24px' }}>
            <Card
              bordered={false}
              style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)', borderRadius: '8px' }}
            >
              <Row justify="space-between" align="middle" style={{ marginBottom: '16px' }}>
                <Col>
                  <Typography.Title level={4} style={{ margin: 0 }}>
                    Amortization Schedule
                  </Typography.Title>
                </Col>
                <Col>
                  <Space size="small">
                    {!screens.xs && (
                      <>
                        <Button
                          type="text"
                          size="small"
                          icon={<DownloadOutlined />}
                          onClick={handleExportCsv}
                        >
                          Export CSV
                        </Button>
                        <Button
                          type="text"
                          size="small"
                          icon={<PrinterOutlined />}
                          onClick={handlePrint}
                        >
                          Print
                        </Button>
                      </>
                    )}
                  </Space>
                </Col>
              </Row>
              <Table
                dataSource={amortizationSchedule}
                columns={tableColumns}
                rowKey="payment_number"
                pagination={false}
                scroll={{ y: 500, x: 'max-content' }}
                size={screens.xs ? 'small' : 'middle'}
                sticky
                rowClassName={(_, index) => (index % 2 === 0 ? 'even-row' : 'odd-row')}
              />
            </Card>
          </div>
        )}

        {!showResults && (
          <div style={{ marginBottom: '24px' }}>
            <Card
              bordered={false}
              style={{
                boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
                borderRadius: '8px',
                textAlign: 'center'
              }}
            >
              <Empty
                description="Enter loan details above and click Calculate to see your payment schedule."
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                style={{ padding: '48px 0' }}
              />
            </Card>
          </div>
        )}
      </div>
    </div>
  );
};

export default LoanCalculatorPage;