import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  MenuItem,
  Select,
  Typography,
  Grid,
  TextField,
  Checkbox,
  FormControlLabel,
  FormGroup,
  Box,
  FormControl,
  FormHelperText,
} from '@mui/material';
import { DocumentDialogProps } from '../AddDocumentDialog';
import { ReactElement, forwardRef, useImperativeHandle, useState } from 'react';
import { PropertiesAPI } from 'types';
import { PropertyOwnerDocumentType } from './PropertyOwnerDocumentDialog';

export interface SellerDisclousureData {
  generalDefects: string;
  roofCondition: string;
  roofAge: string;
  knownRoofLeaks: boolean;
  plumbingIssues: string;
  electricalIssues: string;
  hvacCondition: string;
  hvacAge: string;
  knownLeadPaint: boolean;
  knownAsbestos: boolean;
  knownRadon: boolean;
  pastWaterDamage: string;
  structuralIssues: string;
  neighborhoodNuisances: string;
  propertyLineDisputes: string;
  appliancesIncluded: string;
}

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

// Interface for props of OfferDialogContent
interface SellerDisclousureFormDialogProps {
  onSubmit: (docType: PropertyOwnerDocumentType, disclosure: SellerDisclousureData) => void; // Callback function to send data to parent
  properties: PropertiesAPI[];
  sellerDisclosureErrors: { [key: string]: string };
}

const SellerDisclousureDialogContent = forwardRef<
  SellerDisclousureDialogContentHandle,
  SellerDisclousureFormDialogProps
>(({ onSubmit, properties, sellerDisclosureErrors }, ref) => {
  const [selectedProperty, setSelectedProperty] = useState<PropertiesAPI | null>(null);

  const [generalDefects, setGeneralDefects] = useState<string>('');
  const [roofCondition, setRoofCondition] = useState<string>('');
  const [roofAge, setRoofAge] = useState<string>('');
  const [knownRoofLeaks, setKnownRoofLeaks] = useState<boolean>(false);
  const [plumbingIssues, setPlumbingIssues] = useState<string>('');
  const [electricalIssues, setElectricalIssues] = useState<string>('');
  const [hvacCondition, setHvacCondition] = useState<string>('');
  const [hvacAge, setHvacAge] = useState<string>('');
  const [knownLeadPaint, setKnownLeadPaint] = useState<boolean>(false);
  const [knownAsbestos, setKnownAsbestos] = useState<boolean>(false);
  const [knownRadon, setKnownRadon] = useState<boolean>(false);
  const [pastWaterDamage, setPastWaterDamage] = useState<string>('');
  const [structuralIssues, setStructuralIssues] = useState<string>('');
  const [neighborhoodNuisances, setNeighborhoodNuisances] = useState<string>('');
  const [propertyLineDisputes, setPropertyLineDisputes] = useState<string>('');
  const [appliancesIncluded, setAppliancesIncluded] = useState<string>('');

  const submitForm = () => {
    const formData: SellerDisclousureData = {
      property: selectedProperty?.id,
      general_defects: generalDefects,
      roof_condition: roofCondition,
      roof_age: roofAge,
      known_roof_leaks: knownRoofLeaks,
      plumbing_issues: plumbingIssues,
      electrical_issues: electricalIssues,
      hvac_condition: hvacCondition,
      hvac_age: hvacAge,
      known_lead_paint: knownLeadPaint,
      known_asbestos: knownAsbestos,
      known_radon: knownRadon,
      past_water_damage: pastWaterDamage,
      structural_issues: structuralIssues,
      neighborhood_nuisances: neighborhoodNuisances,
      property_line_disputes: propertyLineDisputes,
      appliances_included: appliancesIncluded,
    };
    onSubmit('seller_disclosure', formData);
  };

  useImperativeHandle(ref, () => ({
    submitForm,
  }));

  console.log(sellerDisclosureErrors);

  return (
    <>
      <Select
        value={selectedProperty?.id || ''}
        label="Property"
        onChange={(e) => {
          const foundProperty = properties.find(
            (property) => property.id === Number(e.target.value),
          );
          setSelectedProperty(foundProperty);
        }}
      >
        {properties.map((property) => (
          <MenuItem value={property.id}>{property.address}</MenuItem>
        ))}
      </Select>
      {selectedProperty && (
        <>
          <Typography variant="subtitle1" gutterBottom>
            For Property: {selectedProperty.address}, {selectedProperty.city},{' '}
            {selectedProperty.state} {selectedProperty.zip_code}
          </Typography>
          <Typography variant="body2" color="textSecondary" sx={{ mb: 2 }}>
            Please disclose any known material defects or information about the property. Honesty is
            crucial to avoid potential legal issues.
          </Typography>

          <Grid container spacing={3}>
            <Grid size={{ xs: 12 }}>
              <TextField
                label="General Known Defects/Issues"
                multiline
                rows={3}
                value={generalDefects}
                onChange={(e) => setGeneralDefects(e.target.value)}
                fullWidth
                margin="normal"
                helperText={`Describe any general issues not covered elsewhere (e.g., drainage problems, pest infestations). ${sellerDisclosureErrors.general_defects}`}
                error={!!sellerDisclosureErrors.general_defects}
              />
            </Grid>

            {/* Property Systems Section */}
            <Grid size={{ xs: 12, sm: 6 }}>
              <Typography variant="h6" sx={{ mt: 2, mb: 1 }}>
                Roof Information
              </Typography>
              <TextField
                label="Roof Condition"
                value={roofCondition}
                onChange={(e) => setRoofCondition(e.target.value)}
                fullWidth
                margin="normal"
                error={!!sellerDisclosureErrors.roof_condition}
                helperText={sellerDisclosureErrors.roof_condition}
              />
              <TextField
                label="Approximate Roof Age (Years)"
                type="number"
                value={roofAge}
                onChange={(e) => setRoofAge(e.target.value)}
                fullWidth
                margin="normal"
                error={!!sellerDisclosureErrors.roof_age}
                helperText={sellerDisclosureErrors.roof_age}
              />
              <FormControl error={!!sellerDisclosureErrors.known_roof_leaks}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={knownRoofLeaks}
                      onChange={(e) => setKnownRoofLeaks(e.target.checked)}
                    />
                  }
                  label="Known Past or Present Roof Leaks?"
                />
                <FormHelperText>{sellerDisclosureErrors.known_roof_leaks}</FormHelperText>
              </FormControl>
            </Grid>

            <Grid size={{ xs: 12, sm: 6 }}>
              <Typography variant="h6" sx={{ mt: 2, mb: 1 }}>
                Major Systems
              </Typography>
              <TextField
                label="Plumbing System Issues"
                multiline
                rows={2}
                value={plumbingIssues}
                onChange={(e) => setPlumbingIssues(e.target.value)}
                fullWidth
                margin="normal"
                error={!!sellerDisclosureErrors.plumbing_issues}
                helperText={sellerDisclosureErrors.plumbing_issues}
              />
              <TextField
                label="Electrical System Issues"
                multiline
                rows={2}
                value={electricalIssues}
                onChange={(e) => setElectricalIssues(e.target.value)}
                fullWidth
                margin="normal"
                error={!!sellerDisclosureErrors.electrical_issues}
                helperText={sellerDisclosureErrors.electrical_issues}
              />
              <TextField
                label="HVAC (Heating, Ventilation, Air Conditioning) Condition"
                value={hvacCondition}
                onChange={(e) => setHvacCondition(e.target.value)}
                fullWidth
                margin="normal"
                error={!!sellerDisclosureErrors.hvac_condition}
                helperText={sellerDisclosureErrors.hvac_condition}
              />
              <TextField
                label="Approximate HVAC Age (Years)"
                type="number"
                value={hvacAge}
                onChange={(e) => setHvacAge(e.target.value)}
                fullWidth
                margin="normal"
                error={!!sellerDisclosureErrors.hvac_age}
                helperText={sellerDisclosureErrors.hvac_age}
              />
            </Grid>

            {/* Environmental & Other Issues */}
            <Grid size={{ xs: 12 }}>
              <Typography variant="h6" sx={{ mt: 2, mb: 1 }}>
                Environmental & Other Issues
              </Typography>
              <FormGroup row>
                <FormControl error={!!sellerDisclosureErrors.known_lead_paint}>
                  <FormControlLabel
                    control={
                      <Checkbox
                        checked={knownLeadPaint}
                        onChange={(e) => setKnownLeadPaint(e.target.checked)}
                      />
                    }
                    label="Known Lead-Based Paint?"
                  />
                  <FormHelperText>{sellerDisclosureErrors.known_lead_paint}</FormHelperText>
                </FormControl>

                <FormControl error={!!sellerDisclosureErrors.known_asbestos}>
                  <FormControlLabel
                    control={
                      <Checkbox
                        checked={knownAsbestos}
                        onChange={(e) => setKnownAsbestos(e.target.checked)}
                      />
                    }
                    label="Known Asbestos?"
                  />
                  <FormHelperText>{sellerDisclosureErrors.known_asbestos}</FormHelperText>
                </FormControl>
                <FormControl error={!!sellerDisclosureErrors.known_radon}>
                  <FormControlLabel
                    control={
                      <Checkbox
                        checked={knownRadon}
                        onChange={(e) => setKnownRadon(e.target.checked)}
                      />
                    }
                    label="Known Radon?"
                  />
                  <FormHelperText>{sellerDisclosureErrors.known_radon}</FormHelperText>
                </FormControl>
              </FormGroup>
              <TextField
                label="Past or Present Water Damage"
                multiline
                rows={2}
                value={pastWaterDamage}
                onChange={(e) => setPastWaterDamage(e.target.value)}
                fullWidth
                margin="normal"
                helperText={`Describe location, cause, and remediation if applicable. ${sellerDisclosureErrors.past_water_damage}`}
                error={!!sellerDisclosureErrors.past_water_damage}
              />
              <TextField
                label="Structural Issues (e.g., foundation, walls)"
                multiline
                rows={2}
                value={structuralIssues}
                onChange={(e) => setStructuralIssues(e.target.value)}
                fullWidth
                margin="normal"
                error={!!sellerDisclosureErrors.structural_issues}
                helperText={sellerDisclosureErrors.structural_issues}
              />
              <TextField
                label="Neighborhood Nuisances (e.g., excessive noise, odors)"
                multiline
                rows={2}
                value={neighborhoodNuisances}
                onChange={(e) => setNeighborhoodNuisances(e.target.value)}
                fullWidth
                margin="normal"
                error={!!sellerDisclosureErrors.neighborhood_nuisances}
                helperText={sellerDisclosureErrors.neighborhood_nuisances}
              />
              <TextField
                label="Property Line Disputes (Past or Present)"
                multiline
                rows={2}
                value={propertyLineDisputes}
                onChange={(e) => setPropertyLineDisputes(e.target.value)}
                fullWidth
                margin="normal"
                error={!!sellerDisclosureErrors.past_water_damage}
                helperText={sellerDisclosureErrors.past_water_damage}
              />
            </Grid>

            {/* Appliances Included */}
            <Grid size={{ xs: 12 }}>
              <Typography variant="h6" sx={{ mt: 2, mb: 1 }}>
                Appliances Included in Sale
              </Typography>
              <TextField
                label="List all appliances included"
                multiline
                rows={3}
                value={appliancesIncluded}
                onChange={(e) => setAppliancesIncluded(e.target.value)}
                fullWidth
                margin="normal"
                placeholder="e.g., Refrigerator, Washer, Dryer, Dishwasher..."
                error={!!sellerDisclosureErrors.appliances_included}
                helperText={sellerDisclosureErrors.appliances_included}
              />
            </Grid>
          </Grid>

          <Box
            sx={{ mt: 3, p: 2, border: '1px dashed #bdbdbd', borderRadius: 1, bgcolor: '#fffde7' }}
          >
            <Typography variant="body2" color="textSecondary">
              By submitting this form, you acknowledge that the information provided is accurate to
              the best of your knowledge and belief.
            </Typography>
          </Box>
        </>
      )}
    </>
  );
});

export default SellerDisclousureDialogContent;
