import {
  Alert,
  Box,
  Button,
  Container,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
} from '@mui/material';
import { ReactElement, useEffect, useMemo, useState } from 'react';

const MortgageCalculator = (): ReactElement => {
  // State variables for mortgage inputs
  const [loanAmount, setLoanAmount] = useState<number | ''>('');
  const [annualInterestRate, setAnnualInterestRate] = useState<number | ''>('');
  const [loanTermYears, setLoanTermYears] = useState<number | ''>('');
  const [pmi, setPmi] = useState<number | ''>(''); // Private Mortgage Insurance (monthly)
  const [hoaFees, setHoaFees] = useState<number | ''>(''); // Homeowners Association Fees (monthly)
  const [homeInsurance, setHomeInsurance] = useState<number | ''>(''); // Home Insurance (monthly)
  const [propertyTax, setPropertyTax] = useState<number | ''>(''); // Property Tax (annual)

  // State variables for calculated results
  const [monthlyPrincipalInterest, setMonthlyPrincipalInterest] = useState<number>(0);
  const [totalMonthlyPayment, setTotalMonthlyPayment] = useState<number>(0);
  const [totalLoanCost, setTotalLoanCost] = useState<number>(0);
  const [totalPrincipalPaid, setTotalPrincipalPaid] = useState<number>(0);
  const [totalInterestPaid, setTotalInterestPaid] = useState<number>(0);
  const [totalPmiPaid, setTotalPmiPaid] = useState<number>(0);
  const [totalHoaFeesPaid, setTotalHoaFeesPaid] = useState<number>(0);
  const [totalHomeInsurancePaid, setTotalHomeInsurancePaid] = useState<number>(0);
  const [totalPropertyTaxPaid, setTotalPropertyTaxPaid] = useState<number>(0);
  const [error, setError] = useState<string | null>(null);

  // Function to calculate the mortgage costs
  const calculateMortgage = () => {
    // Reset error message and previous results
    setError(null);
    setMonthlyPrincipalInterest(0);
    setTotalMonthlyPayment(0);
    setTotalLoanCost(0);
    setTotalPrincipalPaid(0);
    setTotalInterestPaid(0);
    setTotalPmiPaid(0);
    setTotalHoaFeesPaid(0);
    setTotalHomeInsurancePaid(0);
    setTotalPropertyTaxPaid(0);

    // Input validation
    if (loanAmount === '' || annualInterestRate === '' || loanTermYears === '') {
      setError('Please fill in Loan Amount, Annual Interest Rate, and Loan Term.');
      return;
    }
    if (loanAmount <= 0) {
      setError('Loan Amount must be greater than 0.');
      return;
    }
    if (annualInterestRate < 0) {
      setError('Annual Interest Rate cannot be negative.');
      return;
    }
    if (loanTermYears <= 0) {
      setError('Loan Term must be greater than 0.');
      return;
    }

    const p = Number(loanAmount);
    const annualRate = Number(annualInterestRate);
    const years = Number(loanTermYears);

    const monthlyRate = annualRate / 100 / 12; // Convert annual percentage rate to monthly decimal rate
    const numberOfPayments = years * 12; // Total number of monthly payments

    let calculatedMonthlyPI = 0; // Principal & Interest payment

    // Calculate monthly Principal & Interest payment using the loan amortization formula
    if (monthlyRate === 0) {
      // If interest rate is 0, monthly P&I is just principal / number of payments
      calculatedMonthlyPI = p / numberOfPayments;
    } else {
      calculatedMonthlyPI = (p * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -numberOfPayments));
    }

    setMonthlyPrincipalInterest(calculatedMonthlyPI);

    // Calculate total costs over the loan term
    const totalPrincipal = p;
    let totalInterest = 0;
    let currentBalance = p;

    // Simulate interest accumulation for total interest calculation
    for (let i = 1; i <= numberOfPayments; i++) {
      const interestForMonth = currentBalance * monthlyRate;
      totalInterest += interestForMonth;
      const principalPaidForMonth = calculatedMonthlyPI - interestForMonth;
      currentBalance -= principalPaidForMonth;
      if (currentBalance < 0) currentBalance = 0; // Prevent negative balance due to rounding
    }

    // Ensure total interest is non-negative and principal is accurate
    totalInterest = Math.max(0, totalInterest);
    // Recalculate total interest based on total payments if needed for precision
    // totalInterest = (calculatedMonthlyPI * numberOfPayments) - p;

    const monthlyPmi = pmi === '' ? 0 : Number(pmi);
    const monthlyHoa = hoaFees === '' ? 0 : Number(hoaFees);
    const monthlyInsurance = homeInsurance === '' ? 0 : Number(homeInsurance);
    const monthlyPropertyTax = propertyTax === '' ? 0 : Number(propertyTax) / 12; // Convert annual to monthly

    // Calculate total monthly payment including all fees
    const calculatedTotalMonthlyPayment =
      calculatedMonthlyPI + monthlyPmi + monthlyHoa + monthlyInsurance + monthlyPropertyTax;
    setTotalMonthlyPayment(calculatedTotalMonthlyPayment);

    // Calculate total costs over the entire loan term
    const totalPaymentsCount = numberOfPayments; // Total months

    const totalPmi = monthlyPmi * totalPaymentsCount;
    const totalHoa = monthlyHoa * totalPaymentsCount;
    const totalInsurance = monthlyInsurance * totalPaymentsCount;
    const totalPropertyTax = monthlyPropertyTax * totalPaymentsCount;

    setTotalPrincipalPaid(totalPrincipal);
    setTotalInterestPaid(totalInterest);
    setTotalPmiPaid(totalPmi);
    setTotalHoaFeesPaid(totalHoa);
    setTotalHomeInsurancePaid(totalInsurance);
    setTotalPropertyTaxPaid(totalPropertyTax);

    const calculatedTotalLoanCost =
      totalPrincipal + totalInterest + totalPmi + totalHoa + totalInsurance + totalPropertyTax;
    setTotalLoanCost(calculatedTotalLoanCost);
  };

  return (
    <Container maxWidth="lg" sx={{ py: 4 }}>
      <Box sx={{ my: 4, textAlign: 'center' }}>
        <Typography variant="h4" component="h1" gutterBottom sx={{ color: 'background.paper' }}>
          Mortgage Cost Calculator
        </Typography>
        <Typography variant="subtitle1" color="text.secondary">
          Estimate your total monthly mortgage payment and overall loan cost.
        </Typography>
      </Box>

      <Paper elevation={3} sx={{ p: 4, mb: 4 }}>
        <Box
          component="form"
          sx={{
            display: 'grid',
            gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' }, // Two columns on medium screens and up
            gap: 3,
            mb: 3,
          }}
          noValidate
          autoComplete="off"
        >
          {/* Loan Details */}
          <TextField
            label="Loan Amount ($)"
            type="number"
            value={loanAmount}
            onChange={(e) => setLoanAmount(e.target.value === '' ? '' : Number(e.target.value))}
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
          />
          <TextField
            label="Annual Interest Rate (%)"
            type="number"
            value={annualInterestRate}
            onChange={(e) =>
              setAnnualInterestRate(e.target.value === '' ? '' : Number(e.target.value))
            }
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
          />
          <TextField
            label="Loan Term (Years)"
            type="number"
            value={loanTermYears}
            onChange={(e) => setLoanTermYears(e.target.value === '' ? '' : Number(e.target.value))}
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
          />

          {/* Additional Monthly Costs */}
          <TextField
            label="PMI (Monthly $)"
            type="number"
            value={pmi}
            onChange={(e) => setPmi(e.target.value === '' ? '' : Number(e.target.value))}
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
          />
          <TextField
            label="HOA Fees (Monthly $)"
            type="number"
            value={hoaFees}
            onChange={(e) => setHoaFees(e.target.value === '' ? '' : Number(e.target.value))}
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
          />
          <TextField
            label="Home Insurance (Monthly $)"
            type="number"
            value={homeInsurance}
            onChange={(e) => setHomeInsurance(e.target.value === '' ? '' : Number(e.target.value))}
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
          />
          <TextField
            label="Property Tax (Annual $)"
            type="number"
            value={propertyTax}
            onChange={(e) => setPropertyTax(e.target.value === '' ? '' : Number(e.target.value))}
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
          />
        </Box>
        <Button
          variant="contained"
          color="primary"
          onClick={calculateMortgage}
          fullWidth
          size="large"
        >
          Calculate Mortgage Cost
        </Button>
        {error && (
          <Alert severity="error" sx={{ mt: 2, borderRadius: 2 }}>
            {error}
          </Alert>
        )}
      </Paper>

      {totalMonthlyPayment > 0 && (
        <Paper elevation={3} sx={{ p: 4 }}>
          <Typography variant="h5" gutterBottom sx={{ mb: 2 }}>
            Mortgage Summary
          </Typography>
          <Box sx={{ mb: 3 }}>
            <Typography variant="h6" color="primary">
              Estimated Monthly Payment: ${totalMonthlyPayment.toFixed(2)}
            </Typography>
            <Typography variant="body1" sx={{ mt: 2, fontWeight: 'bold' }}>
              Total Cost Breakdown Over {loanTermYears} Years:
            </Typography>
            <Typography variant="body2">
              Total Principal: ${totalPrincipalPaid.toFixed(2)}
            </Typography>
            <Typography variant="body2">Total Interest: ${totalInterestPaid.toFixed(2)}</Typography>
            {pmi !== '' && Number(pmi) > 0 && (
              <Typography variant="body2">Total PMI: ${totalPmiPaid.toFixed(2)}</Typography>
            )}
            {hoaFees !== '' && Number(hoaFees) > 0 && (
              <Typography variant="body2">
                Total HOA Fees: ${totalHoaFeesPaid.toFixed(2)}
              </Typography>
            )}
            {homeInsurance !== '' && Number(homeInsurance) > 0 && (
              <Typography variant="body2">
                Total Home Insurance: ${totalHomeInsurancePaid.toFixed(2)}
              </Typography>
            )}
            {propertyTax !== '' && Number(propertyTax) > 0 && (
              <Typography variant="body2">
                Total Property Tax: ${totalPropertyTaxPaid.toFixed(2)}
              </Typography>
            )}
            <Typography variant="h6" sx={{ mt: 2 }}>
              Overall Loan Cost: ${totalLoanCost.toFixed(2)}
            </Typography>
          </Box>
        </Paper>
      )}
    </Container>
  );
};

export default MortgageCalculator;
