import React, { useState } from 'react';
import {
    Box,
    Typography,
    Card,
    CardContent,
    Divider,
    Button,
    CircularProgress,
    Alert,
} from '@mui/material';
import { AttorneyEngagementLetterData } from 'types';
import { axiosInstance } from '../../../../../axiosApi';

interface AttorneyEngagementLetterDisplayProps {
    letterData: AttorneyEngagementLetterData;
    documentId: number;
    onSignSuccess?: () => void;
}

const AttorneyEngagementLetterDisplay: React.FC<AttorneyEngagementLetterDisplayProps> = ({
    letterData,
    documentId,
    onSignSuccess,
}) => {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [isSigned, setIsSigned] = useState(letterData.is_accepted);

    const handleSign = async () => {
        setLoading(true);
        setError(null);
        try {
            // POST to sign the document
            await axiosInstance.post(`/document/${documentId}/sign/`);
            setIsSigned(true);
            if (onSignSuccess) {
                onSignSuccess();
            }
        } catch (err) {
            console.error('Failed to sign document:', err);
            setError('Failed to sign the document. Please try again.');
        } finally {
            setLoading(false);
        }
    };

    return (
        <Card elevation={3} sx={{ my: 4, borderRadius: 2 }}>
            <CardContent>
                <Typography variant="h5" component="div" gutterBottom sx={{ fontWeight: 'bold' }}>
                    Attorney Engagement Letter
                </Typography>

                <Divider sx={{ my: 2 }} />

                <Box sx={{ maxHeight: '400px', overflowY: 'auto', mb: 3, p: 2, bgcolor: 'grey.50', borderRadius: 1 }}>
                    <Typography variant="body1" paragraph>
                        <strong>ATTORNEY ENGAGEMENT LETTER</strong>
                    </Typography>
                    <Typography variant="body2" paragraph>
                        This Attorney Engagement Letter ("Agreement") is entered into by and between the Client and the Attorney.
                    </Typography>
                    <Typography variant="body2" paragraph>
                        1. <strong>Scope of Representation.</strong> The Attorney agrees to represent the Client in connection with the sale/purchase of the property.
                    </Typography>
                    <Typography variant="body2" paragraph>
                        2. <strong>Fees.</strong> The Client agrees to pay the Attorney for legal services rendered in accordance with the fee schedule attached hereto.
                    </Typography>
                    <Typography variant="body2" paragraph>
                        3. <strong>Duties.</strong> The Attorney will perform all necessary legal services to close the transaction.
                    </Typography>
                    <Typography variant="body2" paragraph>
                        4. <strong>Termination.</strong> Either party may terminate this Agreement at any time upon written notice.
                    </Typography>
                    <Typography variant="body2" paragraph>
                        [This is a boilerplate contract. Specific details will be updated shortly.]
                    </Typography>
                </Box>

                {error && (
                    <Alert severity="error" sx={{ mb: 2 }}>
                        {error}
                    </Alert>
                )}

                <Box sx={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
                    {isSigned ? (
                        <Alert severity="success">
                            Document Signed on {letterData.accepted_at ? new Date(letterData.accepted_at).toLocaleDateString() : 'Unknown Date'}
                        </Alert>
                    ) : (
                        <Button
                            variant="contained"
                            color="primary"
                            onClick={handleSign}
                            disabled={loading}
                            startIcon={loading ? <CircularProgress size={20} /> : null}
                        >
                            {loading ? 'Signing...' : 'Acknowledge & Sign'}
                        </Button>
                    )}
                </Box>
            </CardContent>
        </Card>
    );
};

export default AttorneyEngagementLetterDisplay;
