import React, { useEffect, useState } from 'react';
import { Modal } from '../Modal';
import { Select } from '../Select';
import { Button } from '../Button';
import api from '../../services/api';
import { useAuth } from '../../context/useAuth';
import { useToast } from '../../hooks/useToast';
import type { Project, PaintingScheme } from '../../types';

interface CloneSchemeModalProps {
    isOpen: boolean;
    onClose: () => void;
    onSuccess: () => void;
    schemeToClone?: PaintingScheme;
}

export const CloneSchemeModal: React.FC<CloneSchemeModalProps> = ({ isOpen, onClose, onSuccess, schemeToClone }) => {
    const { isGuest } = useAuth();
    const { showGuestWarning } = useToast();
    const [loading, setLoading] = useState(false);
    const [projects, setProjects] = useState<Project[]>([]);
    const [targetProjectId, setTargetProjectId] = useState('');

    useEffect(() => {
        if (isOpen) {
            api.get('/projects').then(res => {
                // Filter out the project where the scheme currently resides
                const validProjects = res.data.filter((p: Project) => p.id !== schemeToClone?.projectId);
                setProjects(validProjects);
            }).catch(err => console.error("Error loading projects", err));
            setTargetProjectId('');
        }
    }, [isOpen, schemeToClone]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (isGuest()) {
            showGuestWarning();
            return;
        }

        if (!schemeToClone || !targetProjectId) return;

        setLoading(true);
        try {
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            const { id, projectId, ...schemeData } = schemeToClone;

            await api.post('/painting-schemes', {
                ...schemeData,
                projectId: targetProjectId,
                name: schemeData.name // Keep same name or add suffix? Usually same name is fine for new project.
            });

            onSuccess();
            onClose();
        } catch (error) {
            console.error('Error cloning scheme', error);
            alert('Erro ao clonar esquema');
        } finally {
            setLoading(false);
        }
    };

    if (!schemeToClone) return null;

    return (
        <Modal isOpen={isOpen} onClose={onClose} title="Clonar Esquema de Pintura">
            <form onSubmit={handleSubmit} className="space-y-6">
                <div className="bg-surface-soft p-4 rounded-lg text-sm text-text-secondary border border-border">
                    <p className="font-bold text-text-main mb-1">Esquema Original:</p>
                    <p>{schemeToClone.name}</p>
                    <p className="text-xs text-text-muted mt-1">{schemeToClone.type} • {schemeToClone.manufacturer}</p>
                </div>

                <Select
                    name="targetProject"
                    label="Copiar para a Obra/Projeto"
                    options={projects.map(p => ({ label: p.name, value: p.id }))}
                    value={targetProjectId}
                    onChange={(e) => setTargetProjectId(e.target.value)}
                    required
                />

                <div className="flex justify-end gap-2 mt-6">
                    <Button type="button" variant="ghost" onClick={onClose} disabled={loading}>Cancelar</Button>
                    <Button type="submit" disabled={loading || !targetProjectId}>{loading ? 'Clonando...' : 'Confirmar Cópia'}</Button>
                </div>
            </form>
        </Modal>
    );
};
