import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import {
  TextField,
  Button,
  Autocomplete,
  Box,
  Typography,
  Grid,
  CircularProgress,
  InputAdornment,
} from '@mui/material';
import { formatCurrency } from 'utils'; // Assuming this utility function is available
import { axiosInstance } from '../../../../../../axiosApi'; // Assuming axiosInstance is configured
import { PropertiesAPI } from 'types'; // Assuming PropertiesAPI is defined in your types file
import { AxiosResponse } from 'axios';
import { PropertyOwnerDocumentType } from './PropertyOwnerDocumentDialog';

// Define the shape of the offer data to be submitted
export interface OfferData {
  propertyId: number | null;
  offerPrice: number;
  closingDate?: string;
  closingDays?: number;
  contingencies: string;
  parent_offer?: OfferData;
}

// Define the handle for the ref that the parent can use to interact with this component
export interface OfferDialogContentHandle {
  submitForm: () => void;
}

// Define the type for properties passed down
type OfferPropertyType = {
  address: string;
  marketValue: string;
  property_id: number;
};

// Interface for props of OfferDialogContent
interface OfferFormDialogProps {
  onSubmit: (docType: PropertyOwnerDocumentType, offer: OfferData) => void; // Callback function to send data to parent
  offerErrors: { [key: string]: string };
}

const OfferDialogContent = forwardRef<OfferDialogContentHandle, OfferFormDialogProps>(
  ({ onSubmit, offerErrors }, ref) => {
    const [inputValue, setInputValue] = useState('');
    const [options, setOptions] = useState<string[]>([]);
    const [filteredProperties, setFilteredProperties] = useState<OfferPropertyType[]>([]);
    const [loadingProperties, setLoadingProperties] = useState<boolean>(false);

    // State for form fields
    const [selectedProperty, setSelectedProperty] = useState<OfferPropertyType | null>(null);
    const [offerPrice, setOfferPrice] = useState<string>('');
    const [closingDate, setClosingDate] = useState<string>('');
    const [closingDays, setClosingDays] = useState<string>('30'); // Default to 30 days
    const [contingencies, setContingencies] = useState<string>('');

    // Mortgage Calculation States
    const [loanInterestRate, setLoanInterestRate] = useState<string>('7.0'); // Annual percentage
    const [loanTermYears, setLoanTermYears] = useState<string>('30'); // Years
    const [downPaymentPercentage, setDownPaymentPercentage] = useState<string>('20'); // Percentage of offer price

    const [estimatedMonthlyPayment, setEstimatedMonthlyPayment] = useState<string>('N/A');

    // Handle input change for the Autocomplete component, fetching properties
    const handleInputChange = async (event: React.SyntheticEvent, newInputValue: string) => {
      setInputValue(newInputValue);
      if (newInputValue) {
        setLoadingProperties(true);
        try {
          // Fetch properties based on search input
          const { data }: AxiosResponse<PropertiesAPI[]> = await axiosInstance.get(
            `/properties/?search=${newInputValue}`,
          );

          // Map API response to OfferPropertyType
          const mappedResults: OfferPropertyType[] = data.map((item) => ({
            address: item.address,
            marketValue: item.market_value,
            property_id: item.id,
          }));
          setFilteredProperties(mappedResults);
          setOptions(mappedResults.map((item) => item.address)); // Set options for Autocomplete
        } catch (error) {
          console.error('Failed to fetch properties:', error);
          setOptions([]);
          setFilteredProperties([]);
        } finally {
          setLoadingProperties(false);
        }
      } else {
        setOptions([]);
        setFilteredProperties([]);
      }
    };

    // Effect to recalculate mortgage whenever relevant inputs change
    useEffect(() => {
      const calculateMortgage = () => {
        const price = parseFloat(offerPrice);
        const interestRate = parseFloat(loanInterestRate);
        const termYears = parseFloat(loanTermYears);
        const downPaymentPct = parseFloat(downPaymentPercentage);

        // Validate inputs
        if (
          isNaN(price) ||
          price <= 0 ||
          isNaN(interestRate) ||
          isNaN(termYears) ||
          termYears <= 0 ||
          isNaN(downPaymentPct)
        ) {
          setEstimatedMonthlyPayment('N/A');
          return;
        }

        const downPaymentAmount = price * (downPaymentPct / 100);
        const principalLoanAmount = price - downPaymentAmount;

        if (principalLoanAmount <= 0) {
          setEstimatedMonthlyPayment(formatCurrency(0));
          return;
        }

        const monthlyInterestRate = interestRate / 100 / 12;
        const numberOfPayments = termYears * 12;

        let monthlyPayment = 0;
        if (monthlyInterestRate === 0) {
          // Handle zero interest rate scenario
          monthlyPayment = principalLoanAmount / numberOfPayments;
        } else {
          // Standard mortgage formula
          monthlyPayment =
            (principalLoanAmount *
              monthlyInterestRate *
              Math.pow(1 + monthlyInterestRate, numberOfPayments)) /
            (Math.pow(1 + monthlyInterestRate, numberOfPayments) - 1);
        }

        setEstimatedMonthlyPayment(formatCurrency(monthlyPayment));
      };

      calculateMortgage();
    }, [offerPrice, loanInterestRate, loanTermYears, downPaymentPercentage]);

    // Function to handle form submission
    const submitForm = () => {
      // Basic validation
      if (!selectedProperty || !offerPrice) {
        console.error('Validation Error: Please select a property and enter an offer price.');
        // In a real app, you would display a user-friendly error message here (e.g., Snackbar)
        return;
      }

      // Construct the offer data object
      const formData: OfferData = {
        propertyId: selectedProperty.property_id,
        property: selectedProperty.property_id,
        offer_price: parseFloat(offerPrice),
        closing_date: closingDate || undefined,
        closing_days: closingDays ? parseInt(closingDays) : undefined,
        contingencies,
      };

      // Call the onSubmit prop to pass data to the parent
      onSubmit('offer', formData);
    };

    // Expose the submitForm function via useImperativeHandle so parent can call it
    useImperativeHandle(ref, () => ({
      submitForm,
    }));

    console.log(selectedProperty);

    return (
      <Grid container spacing={3}>
        {/* Offer Form Section */}
        <Grid size={{ xs: 12, md: 7 }}>
          <Autocomplete
            value={selectedProperty?.address || null} // Display selected property address or null
            options={options}
            loading={loadingProperties}
            onChange={(event, newValue) => {
              // Find the selected property object from filteredProperties
              const selectedAddr = filteredProperties.find((item) => item.address === newValue);
              setSelectedProperty(selectedAddr || null); // Set selected property or null
            }}
            onInputChange={handleInputChange}
            noOptionsText={'Type the address to search for'}
            renderInput={(params) => (
              <TextField
                {...params}
                label="Select Property"
                variant="outlined"
                fullWidth
                required
                margin="normal"
                InputProps={{
                  ...params.InputProps,
                  endAdornment: (
                    <React.Fragment>
                      {loadingProperties ? <CircularProgress color="inherit" size={20} /> : null}
                      {params.InputProps.endAdornment} {/* Pass existing endAdornment */}
                    </React.Fragment>
                  ),
                }}
              />
            )}
          />
          <TextField
            label="Offer Price"
            type="number"
            value={offerPrice}
            onChange={(e) => setOfferPrice(e.target.value)}
            fullWidth
            required
            margin="normal"
            InputProps={{
              startAdornment: <InputAdornment position="start">$</InputAdornment>,
            }}
            helperText={offerErrors.offer_price}
            error={!!offerErrors.offer_price}
          />
          <TextField
            label="Closing Date (Optional)"
            type="date"
            value={closingDate}
            onChange={(e) => setClosingDate(e.target.value)}
            fullWidth
            margin="normal"
            InputLabelProps={{
              shrink: true,
            }}
            helperText={offerErrors.closing_date}
            error={!!offerErrors.closing_date}
          />
          <Typography variant="body2" color="textSecondary" sx={{ mt: 1, mb: 1 }}>
            OR
          </Typography>
          <TextField
            label="Closing Duration (Days)"
            type="number"
            value={closingDays}
            onChange={(e) => setClosingDays(e.target.value)}
            fullWidth
            margin="normal"
            helperText={offerErrors.closing_days}
            error={!!offerErrors.closing_days}
          />
          <TextField
            label="Other Contingencies (e.g., inspection, financing)"
            multiline
            rows={4}
            value={contingencies}
            onChange={(e) => setContingencies(e.target.value)}
            fullWidth
            margin="normal"
            helperText={offerErrors.contingencies}
            error={!!offerErrors.contingencies}
          />
        </Grid>

        {/* Estimated Mortgage Payment Section */}
        <Grid size={{ xs: 12, md: 5 }}>
          <Box sx={{ p: 2, border: '1px solid #e0e0e0', borderRadius: 2, bgcolor: '#f5f5f5' }}>
            <Typography variant="h6" gutterBottom>
              Estimated Mortgage Payment
            </Typography>
            <TextField
              label="Down Payment (%)"
              type="number"
              value={downPaymentPercentage}
              onChange={(e) => setDownPaymentPercentage(e.target.value)}
              fullWidth
              margin="normal"
              InputProps={{
                endAdornment: <InputAdornment position="end">%</InputAdornment>,
              }}
            />
            <TextField
              label="Annual Interest Rate (%)"
              type="number"
              value={loanInterestRate}
              onChange={(e) => setLoanInterestRate(e.target.value)}
              fullWidth
              margin="normal"
              InputProps={{
                endAdornment: <InputAdornment position="end">%</InputAdornment>,
              }}
            />
            <TextField
              label="Loan Term (Years)"
              type="number"
              value={loanTermYears}
              onChange={(e) => setLoanTermYears(e.target.value)}
              fullWidth
              margin="normal"
            />
            <Box
              sx={{
                mt: 2,
                p: 2,
                border: '1px dashed #bdbdbd',
                borderRadius: 1,
                bgcolor: '#ffffff',
              }}
            >
              <Typography variant="subtitle1">Estimated Monthly Payment (P&I):</Typography>
              <Typography variant="h4" color="primary" sx={{ fontWeight: 'bold' }}>
                {estimatedMonthlyPayment}
              </Typography>
              <Typography variant="caption" color="textSecondary">
                *This is an estimate for Principal & Interest only. It does not include taxes,
                insurance, or HOA fees.
              </Typography>
            </Box>
          </Box>
        </Grid>
      </Grid>
    );
  },
);

export default OfferDialogContent;
