import React, { useState } from 'react';
import { useParams } from 'react-router-dom';
import { Container, Typography, Box, CircularProgress, Alert, TextField, Button, Snackbar } from '@mui/material';
import { useSession, DesireSet, SessionState } from '../hooks/useSession';
import DesireForm from '../components/DesireForm';
import ResultsDisplay from '../components/ResultsDisplay';
import CopyLinkButton from '../components/CopyLinkButton'; // Import CopyLinkButton

const SessionPage = () => {
    const { sessionId } = useParams<{ sessionId: string }>();
    const [session, , sendMessage, clientId, wsError] = useSession(sessionId || '');
    const [expectedResponses, setExpectedResponses] = useState(2);
    const [expectedResponsesError, setExpectedResponsesError] = useState(false);
    const [topic, setTopic] = useState('');
    const [topicError, setTopicError] = useState(false);
    const [description, setDescription] = useState('');
    const [snackbarOpen, setSnackbarOpen] = useState(false);

    React.useEffect(() => {
        if (wsError) {
            setSnackbarOpen(true);
        }
    }, [wsError]);

    const handleSnackbarClose = (event?: React.SyntheticEvent | Event, reason?: string) => {
        if (reason === 'clickaway') {
            return;
        }
        setSnackbarOpen(false);
    };

    const handleSetupSession = () => {
        if (!topic.trim()) {
            setTopicError(true);
            return;
        }
        if (expectedResponses < 2 || expectedResponses > 12) {
            setExpectedResponsesError(true);
            return;
        }
        sendMessage({ type: 'SETUP_SESSION', payload: { expectedResponses, topic, description } });
    };

    const handleSubmitDesires = (desires: { wants: string[], accepts: string[], noGoes: string[], afraidToAsk: string }) => {
        if (!session || !clientId) return;

        const desireSet: DesireSet = {
            participantId: clientId, // Use the clientId from the hook
            wants: desires.wants,
            accepts: desires.accepts,
            noGoes: desires.noGoes,
            afraidToAsk: desires.afraidToAsk,
        };

        sendMessage({
            type: 'SUBMIT_RESPONSE',
            payload: { response: desireSet },
        });
    };

    if (!session) {
        return <Typography>Loading session...</Typography>;
    }

    const remainingResponses = session.expectedResponses - session.submittedCount;
    const hasSubmittedCurrentParticipant = session.responses && session.responses[clientId];

    return (
        <Container maxWidth="md">
            <Box sx={{ mt: 4 }}>

                {session.state === SessionState.SETUP && (
                    <Box sx={{ mt: 4, p: 3, textAlign: 'left' }}>
                        <Typography variant="h5" component="h5" gutterBottom>
                            Harmonize Desires
                        </Typography>
                        <TextField
                            margin="normal"
                            fullWidth
                            id="topic"
                            label="Topic"
                            name="topic"
                            autoFocus
                            required
                            value={topic}
                            onChange={(e) => {
                                setTopic(e.target.value);
                                setTopicError(!e.target.value.trim());
                            }}
                            error={topicError}
                            helperText={topicError ? 'Topic is required' : ''}
                        />
                        <TextField
                            margin="normal"
                            fullWidth
                            id="description"
                            label="Details (Optional)"
                            name="description"
                            multiline
                            rows={3}
                            value={description}
                            onChange={(e) => setDescription(e.target.value)}
                            inputProps={{ maxLength: 500 }}
                            helperText={`Provide more details about what should be addressed in this session (max 500 characters). ${description.length}/500`}
                        />
                        <TextField
                            margin="normal"
                            required
                            fullWidth
                            name="expectedResponses"
                            label="Number of Expected Responses"
                            type="number"
                            id="expectedResponses"
                            value={expectedResponses}
                            onChange={(e) => {
                                const value = parseInt(e.target.value, 10);
                                setExpectedResponses(value);
                                setExpectedResponsesError(value < 2 || value > 12);
                            }}
                            error={expectedResponsesError}
                            helperText={expectedResponsesError ? 'Must be an integer between 2 and 12' : 'Enter the number of participants expected (min 2, max 12)'}
                            InputProps={{
                                inputProps: { min: 1, max: 12 }
                            }}
                        />
                        <Button
                            type="button"
                            variant="contained"
                            sx={{ mt: 2, textTransform: 'none' }}
                            onClick={handleSetupSession}
                        >
                            Start Session
                        </Button>
                    </Box>
                )}

                {session.state !== SessionState.SETUP && (
                    <Box sx={{ mt: 2, p: 2, border: '1px solid #e0e0e0', borderRadius: '4px', backgroundColor: '#f5f5f5' }}>
                    <Box sx={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', width: '100%' }}>
                        <Typography variant="h4" component="h4" gutterBottom>
                            {session.topic || session.sessionId}
                        </Typography>
                        <CopyLinkButton linkToCopy={window.location.href} />
                    </Box>
                        {session.description && (
                            <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                                Details: {session.description}
                            </Typography>
                        )}
                        <Typography variant="body2" color="text.secondary">
                            Expected Responses: {session.expectedResponses}
                        </Typography>
                    </Box>
                )}

                {session.state === SessionState.GATHERING && !hasSubmittedCurrentParticipant && (
                    <DesireForm onSubmit={handleSubmitDesires} externalError={wsError} />
                )}

                {session.state === SessionState.GATHERING && hasSubmittedCurrentParticipant && (
                    <Box sx={{ mt: 4, p: 3, border: '1px dashed grey', borderRadius: '4px', textAlign: 'center' }}>
                        <Typography variant="h6" component="p">
                            Waiting for {remainingResponses} more responses...
                        </Typography>
                        <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                            Your desires have been submitted. The results will be calculated once all participants have responded.
                        </Typography>
                        <Box sx={{ textAlign: 'left', mt: 2 }}>
                            <Typography variant="subtitle1">Your Submitted Desires:</Typography>
                            {session.responses[clientId]?.wants.length > 0 && (
                                <Typography variant="body2"><strong>Wants:</strong> {session.responses[clientId]?.wants.join(', ')}</Typography>
                            )}
                            {session.responses[clientId]?.afraidToAsk && (
                                <Typography variant="body2"><strong>Afraid to Ask:</strong> {session.responses[clientId]?.afraidToAsk}</Typography>
                            )}
                            {session.responses[clientId]?.accepts.length > 0 && (
                                <Typography variant="body2"><strong>Accepts:</strong> {session.responses[clientId]?.accepts.join(', ')}</Typography>
                            )}
                            {session.responses[clientId]?.noGoes.length > 0 && (
                                <Typography variant="body2"><strong>No-Goes:</strong> {session.responses[clientId]?.noGoes.join(', ')}</Typography>
                            )}
                        </Box>
                    </Box>
                )}

                {session.state === SessionState.HARMONIZING && (
                    <Box sx={{ mt: 4, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                        <CircularProgress />
                        <Typography variant="h6" sx={{ mt: 2 }}>Harmonizing Desires...</Typography>
                    </Box>
                )}
                
                {session.state === SessionState.FINAL && session.finalResult && (
                    <ResultsDisplay decision={session.finalResult} />
                )}

                {session.state === SessionState.ERROR && (
                    <Alert severity="error" sx={{ mt: 4 }}>
                        An error occurred during analysis. Please try again.
                    </Alert>
                )}
            </Box>
            <Snackbar open={snackbarOpen} autoHideDuration={6000} onClose={handleSnackbarClose}>
                <Alert onClose={handleSnackbarClose} severity="error" sx={{ width: '100%' }}>
                    {wsError}
                </Alert>
            </Snackbar>
        </Container>
    );
};

export default SessionPage;
