import React, { useState, useEffect } from 'react';
import {
    Box,
    Button,
    DialogActions,
    DialogContent,
    DialogTitle,
    FormControl,
    InputLabel,
    MenuItem,
    Select,
    TextField,
    FormControlLabel,
    Checkbox,
    CircularProgress,
    Alert,
    InputAdornment,
    Grid,
    Paper,
    Typography,
} from '@mui/material';
import { PropertiesAPI, OfferAPI } from 'types';
import { axiosInstance } from '../../../../../../axiosApi';

interface LenderFinancingAgreementDialogContentProps {
    closeDialog: () => void;
    properties: PropertiesAPI[];
}

const LenderFinancingAgreementDialogContent: React.FC<LenderFinancingAgreementDialogContentProps> = ({
    closeDialog,
    properties,
}) => {
    const [selectedPropertyId, setSelectedPropertyId] = useState<number | ''>('');
    const [offers, setOffers] = useState<OfferAPI[]>([]);
    const [selectedOfferId, setSelectedOfferId] = useState<number | ''>('');
    const [loanType, setLoanType] = useState<string>('30_year_fixed');
    const [interestRate, setInterestRate] = useState<string>('');
    const [pmi, setPmi] = useState<boolean>(false);
    const [offerPrice, setOfferPrice] = useState<string>('');
    const [closingDate, setClosingDate] = useState<string>('');
    const [loadingOffers, setLoadingOffers] = useState<boolean>(false);
    const [submitting, setSubmitting] = useState<boolean>(false);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        if (selectedPropertyId) {
            fetchOffers(selectedPropertyId as number);
        } else {
            setOffers([]);
            setSelectedOfferId('');
        }
    }, [selectedPropertyId]);

    const fetchOffers = async (propertyId: number) => {
        setLoadingOffers(true);
        try {
            const response = await axiosInstance.get<OfferAPI[]>(`/offers/?property=${propertyId}`);
            setOffers(response.data);
        } catch (err) {
            console.error('Failed to fetch offers', err);
        } finally {
            setLoadingOffers(false);
        }
    };

    const handleSubmit = async () => {
        if (!selectedPropertyId || !selectedOfferId || !interestRate || !offerPrice || !closingDate) {
            setError('Please fill in all required fields.');
            return;
        }

        setSubmitting(true);
        setError(null);

        const selectedProperty = properties.find((p) => p.id === selectedPropertyId);

        const payload = {
            property: selectedPropertyId,
            document_type: 'lender_financing_agreement',
            sub_document: {
                loan_type: loanType,
                interest_rate: parseFloat(interestRate),
                pmi: pmi,
                offer_price: parseFloat(offerPrice),
                closing_date: closingDate,
                property_address: selectedProperty?.address || '',
                property_owner:
                    selectedProperty?.owner?.user?.first_name + ' ' + selectedProperty?.owner?.user?.last_name ||
                    '',
            },
        };

        try {
            await axiosInstance.post('/document/', payload);
            closeDialog();
            window.location.reload();
        } catch (err) {
            console.error('Failed to create document', err);
            setError('Failed to create document. Please try again.');
        } finally {
            setSubmitting(false);
        }
    };

    const generateAgreementText = () => {
        const selectedProperty = properties.find((p) => p.id === selectedPropertyId);
        const selectedOffer = offers.find((o) => o.id === selectedOfferId);
        const borrowerName = selectedOffer
            ? `${selectedOffer.user.first_name} ${selectedOffer.user.last_name}`
            : '[Borrower Name]';
        const propertyAddress = selectedProperty ? selectedProperty.address : '[Property Address]';
        const currentDate = new Date().toLocaleDateString();

        return `LENDER FINANCING AGREEMENT

Date: ${currentDate}

Property Address: ${propertyAddress}

Borrower: ${borrowerName}
Lender: [Your Lending Institution]

Loan Details:
- Loan Type: ${loanType.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase())}
- Interest Rate: ${interestRate || '[Rate]'}%
- Purchase Price: $${offerPrice || '[Price]'}
- Closing Date: ${closingDate || '[Date]'}
- PMI Included: ${pmi ? 'Yes' : 'No'}

This agreement serves as a preliminary commitment to lend to the Borrower for the purchase of the property located at the address above, subject to the terms and conditions outlined herein.

1. LOAN TERMS
The Lender agrees to provide a loan to the Borrower in the amount necessary to purchase the property, less any down payment, under the loan program specified above.

2. INTEREST RATE
The interest rate specified is subject to market fluctuations until locked in by the Borrower and Lender.

3. CONDITIONS
This agreement is contingent upon:
   a. Satisfactory appraisal of the property.
   b. Verification of Borrower's income and assets.
   c. Clear title to the property.

4. CLOSING
The loan is expected to close on or before the Closing Date specified above.

By proceeding, the Lender acknowledges the intent to finance this transaction.`;
    };

    return (
        <>
            <DialogTitle>Create Lender Financing Agreement</DialogTitle>
            <DialogContent>
                <Grid container spacing={3} sx={{ mt: 1 }}>
                    <Grid size={{ xs: 12, md: 6 }}>
                        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                            {error && <Alert severity="error">{error}</Alert>}

                            <FormControl fullWidth>
                                <InputLabel>Property</InputLabel>
                                <Select
                                    value={selectedPropertyId}
                                    label="Property"
                                    onChange={(e) => setSelectedPropertyId(e.target.value as number)}
                                >
                                    {properties.map((prop) => (
                                        <MenuItem key={prop.id} value={prop.id}>
                                            {prop.address}
                                        </MenuItem>
                                    ))}
                                </Select>
                            </FormControl>

                            <FormControl fullWidth disabled={!selectedPropertyId || loadingOffers}>
                                <InputLabel>Offer</InputLabel>
                                <Select
                                    value={selectedOfferId}
                                    label="Offer"
                                    onChange={(e) => setSelectedOfferId(e.target.value as number)}
                                >
                                    {offers.map((offer) => (
                                        <MenuItem key={offer.id} value={offer.id}>
                                            Offer #{offer.id} - {offer.status}
                                        </MenuItem>
                                    ))}
                                </Select>
                                {loadingOffers && (
                                    <CircularProgress size={20} sx={{ position: 'absolute', right: 30, top: 15 }} />
                                )}
                            </FormControl>

                            <TextField
                                label="Offer Price"
                                type="number"
                                fullWidth
                                value={offerPrice}
                                onChange={(e) => setOfferPrice(e.target.value)}
                                InputProps={{
                                    startAdornment: <InputAdornment position="start">$</InputAdornment>,
                                }}
                            />

                            <TextField
                                label="Closing Date"
                                type="date"
                                fullWidth
                                value={closingDate}
                                onChange={(e) => setClosingDate(e.target.value)}
                                InputLabelProps={{ shrink: true }}
                            />

                            <FormControl fullWidth>
                                <InputLabel>Loan Type</InputLabel>
                                <Select
                                    value={loanType}
                                    label="Loan Type"
                                    onChange={(e) => setLoanType(e.target.value)}
                                >
                                    <MenuItem value="30_year_fixed">30 Year Fixed</MenuItem>
                                    <MenuItem value="15_year_fixed">15 Year Fixed</MenuItem>
                                    <MenuItem value="fha">FHA</MenuItem>
                                    <MenuItem value="va">VA</MenuItem>
                                    <MenuItem value="arm">ARM</MenuItem>
                                </Select>
                            </FormControl>

                            <TextField
                                label="Interest Rate"
                                type="number"
                                fullWidth
                                value={interestRate}
                                onChange={(e) => setInterestRate(e.target.value)}
                                InputProps={{
                                    endAdornment: <InputAdornment position="end">%</InputAdornment>,
                                }}
                            />

                            <FormControlLabel
                                control={<Checkbox checked={pmi} onChange={(e) => setPmi(e.target.checked)} />}
                                label="PMI Included"
                            />
                        </Box>
                    </Grid>
                    <Grid size={{ xs: 12, md: 6 }}>
                        <Paper
                            elevation={3}
                            sx={{
                                p: 3,
                                height: '100%',
                                maxHeight: '600px',
                                overflowY: 'auto',
                                backgroundColor: '#f9f9f9',
                                border: '1px solid #e0e0e0',
                            }}
                        >
                            <Typography variant="h6" gutterBottom sx={{ textAlign: 'center', fontWeight: 'bold' }}>
                                PREVIEW
                            </Typography>
                            <Typography
                                component="pre"
                                sx={{
                                    whiteSpace: 'pre-wrap',
                                    fontFamily: 'monospace',
                                    fontSize: '0.875rem',
                                }}
                            >
                                {generateAgreementText()}
                            </Typography>
                        </Paper>
                    </Grid>
                </Grid>
            </DialogContent>
            <DialogActions>
                <Button onClick={closeDialog}>Cancel</Button>
                <Button onClick={handleSubmit} variant="contained" disabled={submitting}>
                    {submitting ? 'Creating...' : 'Create'}
                </Button>
            </DialogActions>
        </>
    );
};

export default LenderFinancingAgreementDialogContent;
