
import React, { useState } from 'react';
import { Button } from '../components/Button';
import { Input } from '../components/Input';
import { InstitutionForm } from '../components/InstitutionForm';
import { useData } from '../contexts/DataContext';

interface RegisterProps {
    onNavigate: (page: string) => void;
}

export const Register: React.FC<RegisterProps> = ({ onNavigate }) => {
    const { addInstitution } = useData();
    const [formData, setFormData] = useState({
        name: '',
        email: '',
        phone: '',
        password: '',
        confirmPassword: '',
        wantsToAddInstitution: false
    });
    const [agreedToTerms, setAgreedToTerms] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');
    const [success, setSuccess] = useState(false);
    const [showInstitutionForm, setShowInstitutionForm] = useState(false);
    const [tempUserId] = useState(`user-${Date.now()}`);

    const handleChange = (field: string, value: string | boolean) => {
        setFormData(prev => ({ ...prev, [field]: value }));
        setError('');
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsLoading(true);
        setError('');

        // Validação do checkbox de termos
        if (!agreedToTerms) {
            setError('Você precisa concordar com os termos de uso para continuar');
            setIsLoading(false);
            return;
        }

        // Validações
        if (formData.password !== formData.confirmPassword) {
            setError('As senhas não coincidem');
            setIsLoading(false);
            return;
        }

        if (formData.password.length < 6) {
            setError('A senha deve ter no mínimo 6 caracteres');
            setIsLoading(false);
            return;
        }

        // If user wants to add institution, show form
        if (formData.wantsToAddInstitution) {
            setIsLoading(false);
            setShowInstitutionForm(true);
            return;
        }

        // Simular registro (conta será criada como Cliente/EVENT_OWNER automaticamente)
        setTimeout(() => {
            setIsLoading(false);
            setSuccess(true);
            setTimeout(() => {
                onNavigate('entrar');
            }, 2000);
        }, 1500);
    };

    const handleInstitutionSubmit = (institutionData: any) => {
        const newInstitution = {
            ...institutionData,
            id: `inst-${Date.now()}`,
            ownerId: tempUserId
        };
        addInstitution(newInstitution);
        setShowInstitutionForm(false);

        // Complete registration
        setIsLoading(true);
        setTimeout(() => {
            setIsLoading(false);
            setSuccess(true);
            setTimeout(() => {
                onNavigate('entrar');
            }, 2000);
        }, 1500);
    };

    // Show institution form modal
    if (showInstitutionForm) {
        return (
            <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
                <InstitutionForm
                    onCancel={() => {
                        // Apenas fecha o modal e volta para o formulário
                        setShowInstitutionForm(false);
                        // Desmarca a opção de cadastrar universidade
                        setFormData(prev => ({ ...prev, wantsToAddInstitution: false }));
                    }}
                    onSubmit={handleInstitutionSubmit}
                    userId={tempUserId}
                />
            </div>
        );
    }

    if (success) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-white">
                <div className="text-center fade-in">
                    <div className="w-16 h-16 bg-green-500 rounded-full flex items-center justify-center mx-auto mb-4">
                        <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                        </svg>
                    </div>
                    <h2 className="text-2xl font-bold text-gray-900 mb-2">Cadastro realizado com sucesso!</h2>
                    <p className="text-gray-600">Redirecionando para o login...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-white p-4 py-12">
            <div className="w-full max-w-md space-y-8 fade-in">
                {/* Logo */}
                <div className="flex justify-center mb-8">
                    <img
                        src="/logo.png"
                        alt="Photum Formaturas"
                        className="h-20 w-auto object-contain"
                    />
                </div>

                <div className="bg-white rounded-2xl shadow-xl border border-gray-100 p-8">
                    <div className="text-center">
                        <span className="font-bold tracking-widest uppercase text-sm" style={{ color: '#B9CF33' }}>Comece agora</span>
                        <h2 className="mt-3 text-3xl font-serif font-bold text-gray-900">Crie sua conta</h2>
                        <p className="mt-3 text-sm text-gray-600">
                            Já tem uma conta?{' '}
                            <button
                                onClick={() => onNavigate('entrar')}
                                className="font-medium hover:opacity-80 transition-opacity"
                                style={{ color: '#B9CF33' }}
                            >
                                Faça login
                            </button>
                        </p>
                    </div>

                    <form className="mt-8 space-y-5" onSubmit={handleSubmit}>
                        <div className="space-y-4">
                            <Input
                                label="Nome Completo"
                                type="text"
                                required
                                placeholder="João Silva"
                                value={formData.name}
                                onChange={(e) => handleChange('name', e.target.value)}
                            />

                            <Input
                                label="E-mail"
                                type="email"
                                required
                                placeholder="nome@exemplo.com"
                                value={formData.email}
                                onChange={(e) => handleChange('email', e.target.value)}
                            />

                            <Input
                                label="Telefone"
                                type="tel"
                                required
                                placeholder="(00) 00000-0000"
                                value={formData.phone}
                                onChange={(e) => handleChange('phone', e.target.value)}
                                mask="phone"
                            />

                            <Input
                                label="Senha"
                                type="password"
                                required
                                placeholder="••••••••"
                                value={formData.password}
                                onChange={(e) => handleChange('password', e.target.value)}
                            />

                            <Input
                                label="Confirmar Senha"
                                type="password"
                                required
                                placeholder="••••••••"
                                value={formData.confirmPassword}
                                onChange={(e) => handleChange('confirmPassword', e.target.value)}
                                error={error && (error.includes('senha') || error.includes('coincidem')) ? error : undefined}
                            />
                        </div>

                        <div>
                            <div className="flex items-start">
                                <input
                                    type="checkbox"
                                    checked={agreedToTerms}
                                    onChange={(e) => setAgreedToTerms(e.target.checked)}
                                    className="mt-0.5 sm:mt-1 h-4 w-4 flex-shrink-0 border-gray-300 rounded focus:ring-2"
                                    style={{ accentColor: '#B9CF33' }}
                                />
                                <label className="ml-2 text-xs sm:text-sm text-gray-600">
                                    Concordo com os{' '}
                                    <button
                                        type="button"
                                        onClick={() => onNavigate('termos')}
                                        className="hover:opacity-80 transition-opacity underline"
                                        style={{ color: '#B9CF33' }}
                                    >
                                        termos de uso
                                    </button>{' '}
                                    e{' '}
                                    <button
                                        type="button"
                                        onClick={() => onNavigate('privacidade')}
                                        className="hover:opacity-80 transition-opacity underline"
                                        style={{ color: '#B9CF33' }}
                                    >
                                        política de privacidade
                                    </button>
                                </label>
                            </div>
                            {error && error.includes('termos') && (
                                <span className="text-xs text-red-500 mt-1 block ml-6">{error}</span>
                            )}
                        </div>

                        <div className="flex items-start bg-gray-50 border border-gray-200 rounded-lg p-3 sm:p-4">
                            <input
                                type="checkbox"
                                checked={formData.wantsToAddInstitution}
                                onChange={(e) => setFormData(prev => ({ ...prev, wantsToAddInstitution: e.target.checked }))}
                                className="mt-0.5 sm:mt-1 h-4 w-4 flex-shrink-0 border-gray-300 rounded focus:ring-2"
                                style={{ accentColor: '#B9CF33' }}
                            />
                            <label className="ml-2 text-xs sm:text-sm text-gray-700">
                                <span className="font-medium text-xs sm:text-sm">Cadastrar universidade agora (Opcional)</span>
                                <p className="text-[10px] sm:text-xs text-gray-500 mt-1">
                                    Você pode cadastrar sua universidade durante o cadastro ou posteriormente no sistema.
                                    Trabalhamos exclusivamente com eventos fotográficos em universidades.
                                </p>
                            </label>
                        </div>

                        <Button type="submit" className="w-full" size="lg" isLoading={isLoading}>
                            {formData.wantsToAddInstitution ? 'Continuar para Universidade' : 'Criar Conta'}
                        </Button>
                    </form>
                </div>
            </div>
        </div>
    );
};
