import React, { useState } from 'react';
import {
    Box,
    TextField,
    Button,
    Paper,
    Typography,
    Alert,
    CircularProgress,
    InputAdornment,
} from '@mui/material';
import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { Schedule, Notes, Timer } from '@mui/icons-material';
import { meetingService } from '@services/api';
import { toast } from 'react-toastify';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from "@/hooks/useTranslation";

const MeetingForm = () => {
    const { t } = useTranslation();
    const navigate = useNavigate();
    const [formData, setFormData] = useState({
        topic: '',
        agenda: '',
        startTime: new Date(),
        duration: 60,
    });
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');

    const handleChange = (field) => (event) => {
        setFormData({
            ...formData,
            [field]: event.target.value,
        });
    };

    const handleDateChange = (newDate) => {
        setFormData({
            ...formData,
            startTime: newDate,
        });
    };

    const validateForm = () => {
        if (!formData.topic.trim()) {
            setError(t("interviews.form.topicRequired"));
            return false;
        }
        if (formData.duration < 15) {
            setError(t("interviews.form.durationMin"));
            return false;
        }
        if (new Date(formData.startTime) < new Date()) {
            setError(t("interviews.form.startTimeFuture"));
            return false;
        }
        return true;
    };

    // Format date to yyyy-MM-ddTHH:mm:ss (LocalDateTime format - no timezone)
    const formatDateForBackend = (date) => {
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        const hours = String(d.getHours()).padStart(2, '0');
        const minutes = String(d.getMinutes()).padStart(2, '0');
        const seconds = String(d.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError('');

        if (!validateForm()) {
            return;
        }

        setLoading(true);

        try {
            const formattedData = {
                topic: formData.topic.trim(),
                agenda: formData.agenda.trim(),
                startTime: formatDateForBackend(formData.startTime),
                duration: parseInt(formData.duration)
            };

            console.log('Sending formatted data:', formattedData);

            const response = await meetingService.createMeeting(formattedData);
            toast.success(t("interviews.toasts.createSuccess"));
            navigate(`/interviews/${response.data.id}`);
        } catch (err) {
            console.error('Error creating meeting:', err);
            console.error('Error response:', err.response);
            const errorMessage = err.response?.data?.message || t("interviews.toasts.createFailed");
            setError(errorMessage);
            toast.error(errorMessage);
        } finally {
            setLoading(false);
        }
    };

    return (
        <Paper elevation={3} sx={{ p: 4, maxWidth: 700, mx: 'auto' }}>
            <Typography variant="h5" gutterBottom fontWeight="bold">
                {t("interviews.form.pageTitle")}
            </Typography>
            <Typography variant="body2" color="text.secondary" paragraph>
                {t("interviews.form.pageSubtitle")}
            </Typography>

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

            <Box component="form" onSubmit={handleSubmit} sx={{ mt: 3 }}>
                <TextField
                    fullWidth
                    label={t("interviews.form.topicLabel")}
                    value={formData.topic}
                    onChange={handleChange('topic')}
                    required
                    placeholder={t("interviews.form.topicPlaceholder")}
                    InputProps={{
                        startAdornment: (
                            <InputAdornment position="start">
                                <Schedule />
                            </InputAdornment>
                        ),
                    }}
                    sx={{ mb: 3 }}
                />

                <TextField
                    fullWidth
                    label={t("interviews.form.agendaLabel")}
                    multiline
                    rows={4}
                    value={formData.agenda}
                    onChange={handleChange('agenda')}
                    placeholder={t("interviews.form.agendaPlaceholder")}
                    InputProps={{
                        startAdornment: (
                            <InputAdornment position="start" sx={{ alignSelf: 'flex-start', mt: 2 }}>
                                <Notes />
                            </InputAdornment>
                        ),
                    }}
                    sx={{ mb: 3 }}
                />

                <LocalizationProvider dateAdapter={AdapterDateFns}>
                    <DateTimePicker
                        label={t("interviews.form.startTimeLabel")}
                        value={formData.startTime}
                        onChange={handleDateChange}
                        slotProps={{
                            textField: {
                                fullWidth: true,
                                required: true,
                                sx: { mb: 3 }
                            }
                        }}
                        minDateTime={new Date()}
                    />
                </LocalizationProvider>

                <TextField
                    fullWidth
                    type="number"
                    label={t("interviews.form.durationLabel")}
                    value={formData.duration}
                    onChange={handleChange('duration')}
                    required
                    inputProps={{ min: 15, max: 480, step: 15 }}
                    InputProps={{
                        startAdornment: (
                            <InputAdornment position="start">
                                <Timer />
                            </InputAdornment>
                        ),
                    }}
                    helperText={t("interviews.form.durationHelper")}
                    sx={{ mb: 4 }}
                />

                <Box sx={{ display: 'flex', gap: 2 }}>
                    <Button
                        type="submit"
                        variant="contained"
                        fullWidth
                        size="large"
                        disabled={loading}
                        startIcon={loading ? <CircularProgress size={20} /> : <Schedule />}
                    >
                        {loading ? t("interviews.form.submitting") : t("interviews.list.createMeeting")}
                    </Button>
                    <Button
                        variant="outlined"
                        size="large"
                        onClick={() => navigate('/interviews')}
                        disabled={loading}
                    >
                        {t("common.cancel")}
                    </Button>
                </Box>
            </Box>
        </Paper>
    );
};

export default MeetingForm;