import React, { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Button,
  Autocomplete,
  Box,
  Typography,
  Grid,
  CircularProgress,
  InputAdornment,
  Select,
  MenuItem,
} from '@mui/material';
import { formatCurrency } from 'utils';
import { BidAPI, PropertiesAPI, VendorAPI } from 'types';
import { PropertyOwnerDocumentType } from './PropertyOwnerDocumentDialog';

export interface HomeImprovementReceiptData {
  propertyId: number;
  vendorId: number | null;
  dateOfWork: string;
  description: string;
  cost: number;
  receiptFile?: File | null;
}

export interface HomeImprovementReceiptDialogContentHandle {
  submitForm: () => void;
}

interface HomeImprovementReceiptDialogProps {
  onSubmit: (docType: PropertyOwnerDocumentType, receipt: HomeImprovementReceiptData) => void;
  properties: PropertiesAPI[]; // The specific property for which the receipt is being submitted
  vendors: VendorAPI[]; // List of available vendors for autocomplete
  bids: BidAPI[];
  homeImprovmentErrors: { [key: string]: string };
  loadingVendors?: boolean; // Optional: indicate if vendors are still loading
}

const HomeImprovementReciptDialogContent = forwardRef<
  HomeImprovementReceiptDialogContentHandle,
  HomeImprovementReceiptDialogProps
>(({ onSubmit, properties, vendors, bids, homeImprovmentErrors, loadingVendors = false }, ref) => {
  const [selectedProperty, setSelectedProperty] = useState<PropertiesAPI | null>(null);
  const [selectedBid, setSelectedBid] = useState<BidAPI | null>(null);
  const [selectedVendor, setSelectedVendor] = useState<VendorAPI | null>(null);
  const [dateOfWork, setDateOfWork] = useState<string>('');
  const [description, setDescription] = useState<string>('');
  const [cost, setCost] = useState<string>('');
  // const [receiptFile, setReceiptFile] = useState<File | null>(null); // For file upload

  // Reset form when dialog opens/closes
  useEffect(() => {
    if (!open) {
      setSelectedVendor(null);
      setDateOfWork('');
      setDescription('');
      setCost('');
      // setReceiptFile(null);
    }
  }, [open]);

  const submitForm = () => {
    // Basic validation
    if (!selectedProperty) {
      return;
    } else if (!selectedProperty.id || !selectedVendor || !dateOfWork || !cost) {
      return;
    }

    const receiptData: HomeImprovementReceiptData = {
      propertyId: selectedProperty?.id,
      vendorId: selectedVendor.user.id,
      dateOfWork,
      description,
      cost: parseFloat(cost),
      // receiptFile, // Include if handling file upload
    };

    onSubmit('contractor_recipt', receiptData);
  };

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

  console.log(properties);

  const getVendorOptionLabel = (option: VendorAPI) =>
    `${option.business_name} (${option.business_type})`;
  return (
    <Grid size={{ xs: 12, md: 12 }}>
      <Select
        value={selectedProperty?.id || 'Pick a property'}
        placeholder="Pick a property"
        onChange={(e) => {
          console.log(e.target.value);
          console.log(properties);
          console.log(properties.find((property) => property.id === Number(e.target.value)));
          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 }}>
            Record details of home improvements, maintenance, or repairs.
          </Typography>
          {bids.length > 0 ? (
            <>
              <Select
                value={selectedBid}
                label="Bid"
                onChange={(e) => {
                  const foundBid = bids.find((bid) => bid.id === Number(e.target.value));
                  setSelectedBid(foundBid);
                }}
              >
                {bids.map((bid) => (
                  <MenuItem value={bid.id}>{bid.description}</MenuItem>
                ))}
              </Select>

              <Grid container spacing={2}>
                <Grid size={{ xs: 12 }}>
                  <Autocomplete
                    options={vendors}
                    getOptionLabel={getVendorOptionLabel}
                    loading={loadingVendors}
                    onChange={(event, newValue) => {
                      setSelectedVendor(newValue);
                    }}
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        label="Select Vendor"
                        variant="outlined"
                        fullWidth
                        required
                        margin="normal"
                        InputProps={{
                          ...params.InputProps,
                          endAdornment: (
                            <React.Fragment>
                              {loadingVendors ? (
                                <CircularProgress color="inherit" size={20} />
                              ) : null}
                              {params.InputAdornments?.end}
                            </React.Fragment>
                          ),
                        }}
                      />
                    )}
                  />
                </Grid>
                <Grid size={{ xs: 12 }}>
                  <TextField
                    label="Date of Work"
                    type="date"
                    value={dateOfWork}
                    onChange={(e) => setDateOfWork(e.target.value)}
                    fullWidth
                    required
                    margin="normal"
                    InputLabelProps={{
                      shrink: true,
                    }}
                  />
                </Grid>
                <Grid size={{ xs: 12 }}>
                  <TextField
                    label="Description of Work Performed"
                    multiline
                    rows={4}
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    fullWidth
                    margin="normal"
                    helperText="e.g., Replaced water heater, Repaired leaky faucet, Painted living room."
                  />
                </Grid>
                <Grid size={{ xs: 12 }}>
                  <TextField
                    label="Cost of Work"
                    type="number"
                    value={cost}
                    onChange={(e) => setCost(e.target.value)}
                    fullWidth
                    required
                    margin="normal"
                    InputProps={{
                      startAdornment: <InputAdornment position="start">$</InputAdornment>,
                    }}
                  />
                </Grid>
                {/* Uncomment and implement if you need file uploads */}
                <Grid size={{ xs: 12 }}>
                  <Typography variant="subtitle2" sx={{ mt: 1, mb: 0.5 }}>
                    Upload Receipt (Optional)
                  </Typography>
                  <input
                    type="file"
                    onChange={(e) => setReceiptFile(e.target.files ? e.target.files[0] : null)}
                  />
                </Grid>
              </Grid>
            </>
          ) : (
            <Typography>There are no bids to put the recipt against</Typography>
          )}
        </>
      )}
    </Grid>
  );
});

export default HomeImprovementReciptDialogContent;
