import React, { useState } from 'react';
import { Card, CardContent, Typography, TextField, Button, Alert, Tooltip } from '@mui/material';
import { useNavigate } from 'react-router-dom';

interface OfferSubmissionCardProps {
  onOfferSubmit: (
    offerAmount: number,
    closing_days: number,
    contingencies: string,
  ) => Promise<{ status: number; message?: string }>;
  listingStatus: 'active' | 'pending' | 'contingent' | 'sold' | 'off_market';
  listingPrice: number;
  existingOffer?: {
    document_id: string;
  };
}

const OfferSubmissionCard: React.FC<OfferSubmissionCardProps> = ({
  onOfferSubmit,
  listingStatus,
  listingPrice,
  existingOffer,
}) => {
  const [offerAmount, setOfferAmount] = useState<string>('');
  const [closingDuration, setClosingDuration] = useState<string>('');
  const [contingencies, setContingencies] = useState<string>('None');
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const navigate = useNavigate();

  const getClosingDate = () => {
    if (closingDuration) {
      const days = parseInt(closingDuration, 10);
      if (!isNaN(days)) {
        const closingDate = new Date();
        closingDate.setDate(closingDate.getDate() + days);
        return closingDate.toLocaleDateString();
      }
    }
    return '';
  };

  const offerPercentage =
    offerAmount && listingPrice ? (parseFloat(offerAmount) / listingPrice) * 100 : 0;

  if (existingOffer) {
    return (
      <Card>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            Offer Already Submitted
          </Typography>
          <Typography variant="body1" sx={{ mb: 2 }}>
            You have already submitted an offer for this property.
          </Typography>
          <Button
            variant="contained"
            color="primary"
            fullWidth
            onClick={() => navigate(`/documents?selectedDocument=${existingOffer.document_id}`)}
          >
            View Offer
          </Button>
        </CardContent>
      </Card>
    );
  }

  if (listingStatus === 'active') {
    const handleSubmit = async () => {
      const amount = parseFloat(offerAmount);
      const closing_days = parseFloat(closingDuration);
      if (amount > 0 && closing_days) {
        try {
          const response = await onOfferSubmit(amount, closing_days, contingencies);
          if (response.status === 200 || response.status === 201) {
            setSubmitted(true);
            setError(null);
            setTimeout(() => setSubmitted(false), 5000);
          } else {
            setError(response.message || 'An unknown error occurred.');
            setSubmitted(false);
            setTimeout(() => setError(null), 5000);
          }
        } catch (err: any) {
          setError(err.message || 'Failed to submit offer.');
          setSubmitted(false);
          setTimeout(() => setError(null), 5000);
        }
      }
    };

    const isButtonDisabled = !offerAmount || !closingDuration;

    return (
      <Card>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            Submit an Offer
          </Typography>
          <TextField
            fullWidth
            label="Your Offer Amount ($)"
            type="number"
            value={offerAmount}
            onChange={(e) => setOfferAmount(e.target.value)}
            sx={{ mb: 2 }}
            helperText={
              offerPercentage > 0
                ? `This offer is ${offerPercentage.toFixed(2)}% of the listing price.`
                : ''
            }
          />
          <TextField
            fullWidth
            label="Closing Duration (days)"
            type="number"
            value={closingDuration}
            onChange={(e) => setClosingDuration(e.target.value)}
            sx={{ mb: 2 }}
            helperText={closingDuration ? `Estimated closing date: ${getClosingDate()}` : ''}
          />
          <Tooltip title="Typical contingencies include financing, inspection, and appraisal.">
            <TextField
              fullWidth
              label="Contingencies"
              type="text"
              value={contingencies}
              onChange={(e) => setContingencies(e.target.value)}
              sx={{ mb: 2 }}
            />
          </Tooltip>
          <Button
            variant="contained"
            color="primary"
            fullWidth
            onClick={handleSubmit}
            disabled={isButtonDisabled}
          >
            Submit Offer
          </Button>
          {submitted && (
            <Alert severity="success" sx={{ mt: 2 }}>
              Your offer of ${offerAmount} has been submitted!
            </Alert>
          )}
          {error && (
            <Alert severity="error" sx={{ mt: 2 }}>
              {error}
            </Alert>
          )}
        </CardContent>
      </Card>
    );
  } else {
    return (
      <Card>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            Submit an Offer
          </Typography>
          <Typography variant="caption" gutterBottom>
            Offer is not available at the moment because the list is not active
          </Typography>
        </CardContent>
      </Card>
    );
  }
};

export default OfferSubmissionCard;
