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

const NetTermsSheet = (): ReactElement => {
  // State variables for home sale inputs
  const [salePrice, setSalePrice] = useState<number | ''>('');
  const [mortgagePayoff, setMortgagePayoff] = useState<number | ''>('');
  const [agentCommissionRate, setAgentCommissionRate] = useState<number | ''>(6); // Default 6%
  const [titleInsuranceOwner, setTitleInsuranceOwner] = useState<number | ''>(0);
  const [escrowFees, setEscrowFees] = useState<number | ''>(0);
  const [recordingFees, setRecordingFees] = useState<number | ''>(0);
  const [transferTaxes, setTransferTaxes] = useState<number | ''>(0);
  const [attorneyFees, setAttorneyFees] = useState<number | ''>(0);
  const [proratedPropertyTaxes, setProratedPropertyTaxes] = useState<number | ''>(0);
  const [proratedHoaDues, setProratedHoaDues] = useState<number | ''>(0);
  const [sellerConcessions, setSellerConcessions] = useState<number | ''>(0);
  const [otherFees, setOtherFees] = useState<number | ''>(0);

  // State variables for calculated results
  const [totalClosingCosts, setTotalClosingCosts] = useState<number>(0);
  const [netProceeds, setNetProceeds] = useState<number>(0);
  const [error, setError] = useState<string | null>(null);

  // Function to calculate the closing costs and net proceeds
  const calculateNetTerms = () => {
    // Reset error message and previous results
    setError(null);
    setTotalClosingCosts(0);
    setNetProceeds(0);

    // Input validation
    if (salePrice === '') {
      setError('Please enter the Sale Price.');
      return;
    }
    if (Number(salePrice) <= 0) {
      setError('Sale Price must be greater than 0.');
      return;
    }
    if (Number(mortgagePayoff) < 0) {
      setError('Mortgage Payoff cannot be negative.');
      return;
    }
    if (Number(agentCommissionRate) < 0 || Number(agentCommissionRate) > 100) {
      setError('Agent Commission Rate must be between 0 and 100.');
      return;
    }

    const price = Number(salePrice);
    const payoff = mortgagePayoff === '' ? 0 : Number(mortgagePayoff);
    const commissionRate = Number(agentCommissionRate) / 100; // Convert to decimal

    // Calculate agent commission
    const agentCommission = price * commissionRate;

    // Sum up all other closing costs
    const otherFixedCosts =
      (titleInsuranceOwner === '' ? 0 : Number(titleInsuranceOwner)) +
      (escrowFees === '' ? 0 : Number(escrowFees)) +
      (recordingFees === '' ? 0 : Number(recordingFees)) +
      (transferTaxes === '' ? 0 : Number(transferTaxes)) +
      (attorneyFees === '' ? 0 : Number(attorneyFees)) +
      (proratedPropertyTaxes === '' ? 0 : Number(proratedPropertyTaxes)) +
      (proratedHoaDues === '' ? 0 : Number(proratedHoaDues)) +
      (sellerConcessions === '' ? 0 : Number(sellerConcessions)) +
      (otherFees === '' ? 0 : Number(otherFees));

    // Total closing costs
    const calculatedTotalClosingCosts = agentCommission + otherFixedCosts;
    setTotalClosingCosts(calculatedTotalClosingCosts);

    // Calculate net proceeds
    const calculatedNetProceeds = price - payoff - calculatedTotalClosingCosts;
    setNetProceeds(calculatedNetProceeds);

    if (calculatedNetProceeds < 0) {
      setError('Your estimated net proceeds are negative. You might owe money at closing.');
    }
  };

  return (
    <Container maxWidth="lg" sx={{ py: 4 }}>
      <Box sx={{ my: 4, textAlign: 'center' }}>
        <Typography variant="h4" component="h1" gutterBottom sx={{ color: 'background.paper' }}>
          Home Sale Closing Costs Calculator
        </Typography>
        <Typography variant="subtitle1" color="text.secondary">
          Estimate your net proceeds from a home sale by calculating closing costs.
        </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"
        >
          {/* Primary Sale Details */}
          <TextField
            label="Home Sale Price ($)"
            type="number"
            value={salePrice}
            onChange={(e) => setSalePrice(e.target.value === '' ? '' : Number(e.target.value))}
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
            InputProps={{ startAdornment: <InputAdornment position="start">$</InputAdornment> }}
          />
          <TextField
            label="Mortgage Payoff Amount ($)"
            type="number"
            value={mortgagePayoff}
            onChange={(e) => setMortgagePayoff(e.target.value === '' ? '' : Number(e.target.value))}
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
            InputProps={{ startAdornment: <InputAdornment position="start">$</InputAdornment> }}
          />

          {/* Commission and Other Fees */}
          <TextField
            label="Agent Commission Rate (%)"
            type="number"
            value={agentCommissionRate}
            onChange={(e) =>
              setAgentCommissionRate(e.target.value === '' ? '' : Number(e.target.value))
            }
            fullWidth
            variant="outlined"
            inputProps={{ min: 0, max: 100 }}
            InputProps={{ endAdornment: <InputAdornment position="end">%</InputAdornment> }}
          />
          <TextField
            label="Title Insurance (Owner's Policy) ($)"
            type="number"
            value={titleInsuranceOwner}
            onChange={(e) =>
              setTitleInsuranceOwner(e.target.value === '' ? '' : Number(e.target.value))
            }
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
            InputProps={{ startAdornment: <InputAdornment position="start">$</InputAdornment> }}
          />
          <TextField
            label="Escrow Fees ($)"
            type="number"
            value={escrowFees}
            onChange={(e) => setEscrowFees(e.target.value === '' ? '' : Number(e.target.value))}
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
            InputProps={{ startAdornment: <InputAdornment position="start">$</InputAdornment> }}
          />
          <TextField
            label="Recording Fees ($)"
            type="number"
            value={recordingFees}
            onChange={(e) => setRecordingFees(e.target.value === '' ? '' : Number(e.target.value))}
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
            InputProps={{ startAdornment: <InputAdornment position="start">$</InputAdornment> }}
          />
          <TextField
            label="Transfer Taxes / Deed Stamps ($)"
            type="number"
            value={transferTaxes}
            onChange={(e) => setTransferTaxes(e.target.value === '' ? '' : Number(e.target.value))}
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
            InputProps={{ startAdornment: <InputAdornment position="start">$</InputAdornment> }}
          />
          <TextField
            label="Attorney Fees ($)"
            type="number"
            value={attorneyFees}
            onChange={(e) => setAttorneyFees(e.target.value === '' ? '' : Number(e.target.value))}
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
            InputProps={{ startAdornment: <InputAdornment position="start">$</InputAdornment> }}
          />
          <TextField
            label="Prorated Property Taxes ($)"
            type="number"
            value={proratedPropertyTaxes}
            onChange={(e) =>
              setProratedPropertyTaxes(e.target.value === '' ? '' : Number(e.target.value))
            }
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
            InputProps={{ startAdornment: <InputAdornment position="start">$</InputAdornment> }}
          />
          <TextField
            label="Prorated HOA Dues ($)"
            type="number"
            value={proratedHoaDues}
            onChange={(e) =>
              setProratedHoaDues(e.target.value === '' ? '' : Number(e.target.value))
            }
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
            InputProps={{ startAdornment: <InputAdornment position="start">$</InputAdornment> }}
          />
          <TextField
            label="Seller Concessions ($)"
            type="number"
            value={sellerConcessions}
            onChange={(e) =>
              setSellerConcessions(e.target.value === '' ? '' : Number(e.target.value))
            }
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
            InputProps={{ startAdornment: <InputAdornment position="start">$</InputAdornment> }}
          />
          <TextField
            label="Other Fees ($)"
            type="number"
            value={otherFees}
            onChange={(e) => setOtherFees(e.target.value === '' ? '' : Number(e.target.value))}
            fullWidth
            variant="outlined"
            inputProps={{ min: 0 }}
            InputProps={{ startAdornment: <InputAdornment position="start">$</InputAdornment> }}
          />
        </Box>
        <Button
          variant="contained"
          color="primary"
          onClick={calculateNetTerms}
          fullWidth
          size="large"
        >
          Calculate Net Proceeds
        </Button>
        {error && (
          <Alert severity="error" sx={{ mt: 2, borderRadius: 2 }}>
            {error}
          </Alert>
        )}
      </Paper>

      {totalClosingCosts > 0 || netProceeds !== 0 ? ( // Display results if calculations have been made
        <Paper elevation={3} sx={{ p: 4 }}>
          <Typography variant="h5" gutterBottom sx={{ mb: 2 }}>
            Sale Summary
          </Typography>
          <Box sx={{ mb: 3 }}>
            <Typography variant="h6" color="primary">
              Estimated Total Closing Costs: ${totalClosingCosts.toFixed(2)}
            </Typography>
            <Typography variant="h6" color={netProceeds >= 0 ? 'primary' : 'error'} sx={{ mt: 1 }}>
              Estimated Net Proceeds: ${netProceeds.toFixed(2)}
            </Typography>
            <Typography variant="body2" sx={{ mt: 2 }}>
              *This is an estimate. Actual closing costs and net proceeds may vary. Consult with
              your real estate agent or attorney for precise figures.
            </Typography>
          </Box>
        </Paper>
      ) : null}
    </Container>
  );
};

export default NetTermsSheet;
