import React, { useState } from 'react';
import {
  Card,
  CardContent,
  Typography,
  Grid,
  Box,
  ImageList,
  ImageListItem,
  ImageListItemBar,
  Button,
  TextField,
  Alert,
  IconButton,
  Stack,
} from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Cancel';
import AddPhotoAlternateIcon from '@mui/icons-material/AddPhotoAlternate';
import DeleteForeverIcon from '@mui/icons-material/DeleteForever';
import { axiosInstance } from '../../../../../axiosApi';

import { PropertiesAPI } from 'types';
import MapComponent from '../../../../base/MapComponent';
import FormattedListingText from 'components/base/FormattedListingText';
import { useNavigate } from 'react-router-dom';

interface PropertyDetailCardProps {
  property: PropertiesAPI;
  onSave: (updatedProperty: PropertiesAPI) => void;
  isPublicPage?: boolean;
  isOwnerView?: boolean; // True if the current user is the owner, allows editing
  onDelete?: (propertyId: number) => void;
}

const PropertyDetailCard: React.FC<PropertyDetailCardProps> = ({
  property,
  onSave,
  isPublicPage,
  isOwnerView = false,
  onDelete = null,
}) => {
  const [isEditing, setIsEditing] = useState(false);
  const [isGenerating, setIsGernerating] = useState<boolean>(false);
  const [editedProperty, setEditedProperty] = useState<PropertiesAPI>(property);
  const [formErrors, setFormErrors] = useState<{ [key: string]: string }>({});

  // Ensure latitude and longitude are defined, use defaults if not available
  const displayLat = Number(editedProperty.latitude) ?? 34.0522; // Default to LA for demo
  const displayLng = Number(editedProperty.longitude) ?? -118.2437; // Default to LA for demo
  const navigate = useNavigate();

  const handleEditToggle = () => {
    if (isEditing) {
      setEditedProperty(property); // Revert changes on cancel
      setFormErrors({});
    }
    setIsEditing(!isEditing);
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setEditedProperty((prev) => ({
      ...prev,
      [name]: value,
    }));
    if (formErrors[name]) {
      setFormErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  const handleNumericChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    const numValue = parseFloat(value);
    setEditedProperty((prev) => ({
      ...prev,
      [name]: isNaN(numValue) ? '' : numValue,
    }));
    if (formErrors[name]) {
      setFormErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  const handleFeaturesChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const value = e.target.value;
    setEditedProperty((prev) => ({
      ...prev,
      features: value
        .split(',')
        .map((f) => f.trim())
        .filter((f) => f),
    }));
  };

  const handleViewPublicListing = () => {
    navigate(`/property/${property.id}/`);
  };

  const handlePictureUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      const filesArray = Array.from(e.target.files);
      // In a real app, you'd upload these files to a server and get URLs back
      console.log(filesArray);
      filesArray.map((file) => {
        const formData = new FormData();
        formData.append('image', file);
        formData.append('Property', property.id.toString());

        const response = axiosInstance.post('/properties/pictures/', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });
        console.log(response);
      });
    }
  };

  const validateForm = () => {
    const errors: { [key: string]: string } = {};
    if (!editedProperty.address.trim()) errors.address = 'Address is required.';
    if (!editedProperty.city.trim()) errors.city = 'City is required.';
    if (!editedProperty.state.trim()) errors.state = 'State is required.';
    if (!editedProperty.zip_code.trim()) errors.zip_code = 'Zip code is required.';
    if (editedProperty.sq_ft !== undefined && editedProperty.sq_ft <= 0)
      errors.sq_ft = 'Square footage must be positive.';
    if (editedProperty.num_bedrooms !== undefined && editedProperty.num_bedrooms < 0)
      errors.num_bedrooms = 'Bedrooms cannot be negative.';
    if (editedProperty.num_bathrooms !== undefined && editedProperty.num_bathrooms < 0)
      errors.num_bathrooms = 'Bathrooms cannot be negative.';

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleSave = () => {
    if (validateForm()) {
      onSave(editedProperty);
      setIsEditing(false);
    }
  };

  const handleDelete = () => {
    if (isOwnerView && !isPublicPage && onDelete) {
      onDelete(property.id);
    }
  };

  const generateDescription = async () => {
    setIsGernerating(true);

    const response = await axiosInstance.put(`/property-description-generator/${property.id}/`);
    setEditedProperty((prev) => ({
      ...prev,
      description: response.data.description,
    }));
    setIsGernerating(false);
  };

  return (
    <Card sx={{ mt: 3, p: 2 }}>
      <CardContent>
        <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
          <Typography variant="h5" component="h2">
            {isEditing ? 'Edit Property Details' : property.address}
          </Typography>
          {isOwnerView &&
            !isPublicPage &&
            (isEditing ? (
              <Box>
                <IconButton color="primary" onClick={handleDelete}>
                  <DeleteForeverIcon />
                </IconButton>
                <IconButton color="primary" onClick={handleSave}>
                  <SaveIcon />
                </IconButton>
                <IconButton color="secondary" onClick={handleEditToggle}>
                  <CancelIcon />
                </IconButton>
              </Box>
            ) : (
              <IconButton color="primary" onClick={handleEditToggle}>
                <EditIcon />
              </IconButton>
            ))}
        </Box>

        <Grid container spacing={3}>
          {/* Property Address & Basic Info */}
          <Grid size={{ xs: 12 }}>
            {isEditing ? (
              <Grid container spacing={2}>
                <Grid size={{ xs: 8 }}>
                  <TextField
                    fullWidth
                    label="Address"
                    name="address"
                    value={editedProperty.address}
                    onChange={handleChange}
                    required
                    error={!!formErrors.address}
                    helperText={formErrors.address}
                  />
                </Grid>
                <Grid size={{ xs: 12, sm: 4 }}>
                  <TextField
                    fullWidth
                    label="City"
                    name="city"
                    value={editedProperty.city}
                    onChange={handleChange}
                    required
                    error={!!formErrors.city}
                    helperText={formErrors.city}
                  />
                </Grid>
                <Grid size={{ xs: 12, sm: 4 }}>
                  <TextField
                    fullWidth
                    label="State"
                    name="state"
                    value={editedProperty.state}
                    onChange={handleChange}
                    required
                    error={!!formErrors.state}
                    helperText={formErrors.state}
                  />
                </Grid>
                <Grid size={{ xs: 12, sm: 4 }}>
                  <TextField
                    fullWidth
                    label="Zip Code"
                    name="zip_code"
                    value={editedProperty.zip_code}
                    onChange={handleChange}
                    required
                    error={!!formErrors.zip_code}
                    helperText={formErrors.zip_code}
                  />
                </Grid>
              </Grid>
            ) : (
              <Stack direction="row">
                <Typography variant="h6">
                  {property.street}, {property.city}, {property.state} {property.zip_code}
                </Typography>
                {isOwnerView && !isPublicPage && (
                  <Button onClick={handleViewPublicListing}>View Public Listing</Button>
                )}
              </Stack>
            )}
          </Grid>

          {/* Pictures */}
          <Grid size={{ xs: 12, md: 6 }}>
            <Typography variant="subtitle1" gutterBottom>
              Pictures:
            </Typography>
            {editedProperty.pictures && editedProperty.pictures.length > 0 ? (
              <ImageList
                cols={editedProperty.pictures.length > 1 ? 2 : 1}
                rowHeight={164}
                sx={{ maxWidth: 500 }}
              >
                {editedProperty.pictures.map((item, index) => (
                  <ImageListItem key={item.id}>
                    <img
                      srcSet={`${item.image}?w=164&h=164&fit=crop&auto=format 1x, ${item.image}?w=164&h=164&fit=crop&auto=format&dpr=2 2x`}
                      src={`${item.image}?w=164&h=164&fit=crop&auto=format`}
                      alt={`Property image ${index + 1}`}
                      loading="lazy"
                    />
                    <ImageListItemBar title={`Image ${index + 1}`} />
                  </ImageListItem>
                ))}
              </ImageList>
            ) : (
              <Typography variant="body2" color="textSecondary">
                No pictures available.
              </Typography>
            )}
            {isEditing && (
              <Button
                variant="outlined"
                component="label"
                startIcon={<AddPhotoAlternateIcon />}
                sx={{ mt: 2 }}
              >
                Add More Pictures
                <input
                  type="file"
                  hidden
                  multiple
                  accept="image/*"
                  onChange={handlePictureUpload}
                />
              </Button>
            )}
          </Grid>

          {/* Description */}
          <Grid size={{ xs: 12, md: 6 }}>
            <Typography variant="subtitle1" gutterBottom>
              Description:
            </Typography>
            {isEditing ? (
              <Stack direction="column">
                <TextField
                  fullWidth
                  multiline
                  rows={4}
                  label="Description"
                  name="description"
                  value={editedProperty.description}
                  onChange={handleChange}
                />

                <Button variant="contained" onClick={generateDescription} disabled={isGenerating}>
                  Generate a description
                </Button>
              </Stack>
            ) : (
              <FormattedListingText text={property.description} />
              // <Typography variant="body2" color="textSecondary">
              //     {property.description || 'No description provided.'}
              // </Typography>
            )}
          </Grid>

          {/* Stats */}
          <Grid size={{ xs: 12, md: 6 }}>
            <Typography variant="subtitle1" gutterBottom>
              Stats:
            </Typography>
            {isEditing ? (
              <Grid container spacing={2}>
                <Grid size={{ xs: 6 }}>
                  <TextField
                    fullWidth
                    label="Sq Ft"
                    name="sq_ft"
                    type="number"
                    value={editedProperty.sq_ft || ''}
                    onChange={handleNumericChange}
                    error={!!formErrors.sq_ft}
                    helperText={formErrors.sq_ft}
                  />
                </Grid>
                <Grid size={{ xs: 6 }}>
                  <TextField
                    fullWidth
                    label="Bedrooms"
                    name="num_bedrooms"
                    type="number"
                    value={editedProperty.num_bedrooms || ''}
                    onChange={handleNumericChange}
                    error={!!formErrors.num_bedrooms}
                    helperText={formErrors.num_bedrooms}
                  />
                </Grid>
                <Grid size={{ xs: 6 }}>
                  <TextField
                    fullWidth
                    label="Bathrooms"
                    name="num_bathrooms"
                    type="number"
                    value={editedProperty.num_bathrooms || ''}
                    onChange={handleNumericChange}
                    error={!!formErrors.num_bathrooms}
                    helperText={formErrors.num_bathrooms}
                  />
                </Grid>
                <Grid size={{ xs: 6 }}>
                  <TextField
                    fullWidth
                    label="Features (comma-separated)"
                    name="features"
                    value={editedProperty.features.join(', ') || ''}
                    onChange={handleFeaturesChange}
                  />
                </Grid>
                <Grid size={{ xs: 6 }}>
                  <TextField
                    fullWidth
                    label="Market Value"
                    name="market_value"
                    value={editedProperty.market_value}
                    onChange={handleChange}
                  />
                </Grid>
                <Grid size={{ xs: 6 }}>
                  <TextField
                    fullWidth
                    label="Loan Amount"
                    name="loan_amount"
                    value={editedProperty.loan_amount}
                    onChange={handleChange}
                  />
                </Grid>
                <Grid size={{ xs: 12, sm: 6 }}>
                  <TextField
                    fullWidth
                    label="Loan Term (years)"
                    name="loan_term"
                    type="number"
                    value={editedProperty.loan_term || ''}
                    onChange={handleNumericChange}
                  />
                </Grid>
                <Grid size={{ xs: 12, sm: 6 }}>
                  <TextField
                    fullWidth
                    label="Loan Start Date"
                    name="loan_start_date"
                    type="date"
                    InputLabelProps={{ shrink: true }}
                    value={editedProperty.loan_start_date}
                    onChange={handleChange}
                  />
                </Grid>
              </Grid>
            ) : (
              <Box>
                <Typography variant="body2">Sq Ft: {property.sq_ft || 'N/A'}</Typography>
                <Typography variant="body2">Bedrooms: {property.num_bedrooms || 'N/A'}</Typography>
                <Typography variant="body2">
                  Bathrooms: {property.num_bathrooms || 'N/A'}
                </Typography>
                <Typography variant="body2">
                  Features:{' '}
                  {property.features && property.features.length > 0
                    ? property.features.join(', ')
                    : 'None'}
                </Typography>
                <Typography variant="body2">
                  Market Value: ${property.market_value || 'N/A'}
                </Typography>
                <Typography variant="body2">
                  Loan Amount: ${property.loan_amount || 'N/A'}
                </Typography>
                <Typography variant="body2">
                  Loan Term: {property.loan_term ? `${property.loan_term} years` : 'N/A'}
                </Typography>
                <Typography variant="body2">
                  Loan Start Date: {property.loan_start_date || 'N/A'}
                </Typography>
              </Box>
            )}
          </Grid>

          {/* Map */}
          <Grid size={{ xs: 12, md: 6 }}>
            <Typography variant="subtitle1" gutterBottom>
              Location on Map:
            </Typography>
            <MapComponent lat={displayLat} lng={displayLng} address={property.address} />
          </Grid>
        </Grid>
        {Object.keys(formErrors).length > 0 && (
          <Alert severity="error" sx={{ mt: 2 }}>
            Please correct the errors in the form.
          </Alert>
        )}
      </CardContent>
    </Card>
  );
};

export default PropertyDetailCard;
