'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { ShieldCheck, ArrowRight, Building2, CheckCircle2, Copy, ExternalLink } from 'lucide-react';

export default function MerchantRegisterPage() {
    const [name, setName] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');
    const [success, setSuccess] = useState<any>(null);
    const router = useRouter();

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

        try {
            const response = await fetch('/api/merchants/register', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name })
            });

            const data = await response.json();

            if (response.ok) {
                setSuccess(data);
            } else {
                setError(data.error || 'Kayıt sırasında bir hata oluştu.');
            }
        } catch (err) {
            setError('Bağlantı hatası. Lütfen tekrar deneyin.');
        } finally {
            setIsLoading(false);
        }
    };

    if (success) {
        return (
            <div className="min-h-screen bg-[#F8FAFC] flex flex-col items-center justify-center p-6">
                <div className="w-full max-w-2xl space-y-8 animate-in zoom-in duration-500">
                    <div className="text-center space-y-4">
                        <div className="w-24 h-24 bg-emerald-500 rounded-[32px] flex items-center justify-center text-white mx-auto shadow-2xl shadow-emerald-100 mb-6">
                            <CheckCircle2 size={48} />
                        </div>
                        <h1 className="text-4xl font-black text-gray-900 tracking-tight uppercase italic">Tebrikler!</h1>
                        <p className="text-gray-400 font-bold uppercase tracking-[0.3em] text-[10px]">Hesabınız Başarıyla Oluşturuldu</p>
                    </div>

                    <div className="bg-white p-12 rounded-[50px] border border-gray-100 shadow-2xl space-y-10 relative overflow-hidden">
                        <div className="absolute top-0 right-0 p-8 opacity-5">
                            <Building2 size={120} />
                        </div>
                        
                        <div className="space-y-6">
                            <div className="p-8 bg-blue-50 rounded-[30px] border border-blue-100 space-y-4">
                                <p className="text-[10px] font-black text-blue-600 uppercase tracking-widest text-center">Firma Yönetim Paneliniz</p>
                                <div className="flex items-center justify-center gap-4">
                                    <code className="text-lg font-black text-gray-900 tracking-tighter">/merchant/{success.shortId}</code>
                                    <button 
                                        onClick={() => navigator.clipboard.writeText(`${window.location.origin}/merchant/${success.shortId}`)}
                                        className="p-2 hover:bg-white rounded-lg transition-colors border border-transparent hover:border-blue-200"
                                    >
                                        <Copy size={16} className="text-blue-600" />
                                    </button>
                                </div>
                            </div>

                            <div className="p-8 bg-red-50 rounded-[30px] border border-red-100 space-y-4">
                                <div className="flex flex-col items-center text-center space-y-2">
                                    <p className="text-[10px] font-black text-red-600 uppercase tracking-widest italic">Kritik Güvenlik Anahtarı</p>
                                    <p className="text-[9px] text-red-400 font-bold uppercase leading-relaxed max-w-xs">
                                        Bu anahtarı güvenli bir yere kaydedin. Sisteme giriş yapmak için tek yönteminiz budur. Bir daha görüntülenemez!
                                    </p>
                                </div>
                                <div className="flex items-center justify-center gap-4 bg-white/50 p-4 rounded-2xl border border-red-50">
                                    <code className="text-sm font-mono font-bold text-gray-900 break-all text-center">{success.apiKey}</code>
                                    <button 
                                        onClick={() => navigator.clipboard.writeText(success.apiKey)}
                                        className="p-2 hover:bg-white rounded-lg transition-colors shrink-0"
                                    >
                                        <Copy size={16} className="text-red-600" />
                                    </button>
                                </div>
                            </div>
                        </div>

                        <button
                            onClick={() => router.push(`/merchant/${success.shortId}/login`)}
                            className="w-full py-6 bg-gray-900 text-white rounded-[24px] font-black text-xs uppercase tracking-[0.2em] hover:bg-black transition shadow-2xl flex items-center justify-center gap-3"
                        >
                            Paneli Aç ve Başla
                            <ExternalLink size={18} />
                        </button>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-[#F8FAFC] flex flex-col items-center justify-center p-6">
            <div className="w-full max-w-md space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-700">
                <div className="text-center space-y-4">
                    <div className="w-20 h-20 bg-gray-900 rounded-[32px] flex items-center justify-center text-white mx-auto shadow-2xl shadow-gray-200 mb-6">
                        <Building2 size={32} />
                    </div>
                    <h1 className="text-3xl font-black text-gray-900 tracking-tight uppercase italic">Firma Kaydı</h1>
                    <p className="text-gray-400 font-bold uppercase tracking-widest text-[10px]">P2CGateway Merchant Network'e Katılın</p>
                </div>

                <div className="bg-white p-10 rounded-[40px] border border-gray-100 shadow-xl shadow-gray-200/50 space-y-8">
                    <div className="space-y-2">
                        <p className="text-sm font-black text-gray-900 leading-tight">Firma adınızı belirleyin</p>
                        <p className="text-[10px] text-gray-400 font-bold uppercase tracking-wider leading-relaxed">
                            Müşterileriniz ödeme sayfasında bu ismi görecektir.
                        </p>
                    </div>

                    <form onSubmit={handleSubmit} className="space-y-6">
                        <div className="space-y-3">
                            <input
                                type="text"
                                required
                                minLength={3}
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                                placeholder="Örn: Ayris Teknoloji"
                                className="w-full px-6 py-4 bg-gray-50 border-2 border-transparent focus:border-blue-500 focus:bg-white rounded-[24px] outline-none transition-all font-bold text-gray-900 placeholder:text-gray-300"
                            />
                            {error && <p className="text-[10px] text-red-500 font-black uppercase tracking-widest pl-2">{error}</p>}
                        </div>

                        <div className="bg-blue-50/50 p-4 rounded-2xl space-y-2">
                            <p className="text-[9px] text-blue-600/70 font-bold uppercase leading-relaxed">
                                * Kayıt olduktan sonra size özel bir yönetim paneli ve API anahtarı tahsis edilecektir.
                            </p>
                        </div>

                        <button
                            type="submit"
                            disabled={isLoading}
                            className="w-full py-5 bg-blue-600 text-white rounded-2xl font-black text-xs uppercase tracking-[0.2em] hover:bg-blue-700 transition shadow-xl shadow-blue-100 disabled:opacity-50 flex items-center justify-center gap-2"
                        >
                            {isLoading ? 'Kaydediliyor...' : 'Şimdi Katıl'}
                            {!isLoading && <ArrowRight size={16} />}
                        </button>
                    </form>
                </div>

                <div className="text-center pt-4">
                    <button
                        onClick={() => router.push('/')}
                        className="text-[10px] font-black text-gray-400 uppercase tracking-widest hover:text-gray-900 transition"
                    >
                        Giriş Sayfasına Dön
                    </button>
                </div>
            </div>

            <div className="mt-20 flex items-center gap-3 px-6 py-2 bg-emerald-50 rounded-full border border-emerald-100">
                <ShieldCheck size={14} className="text-emerald-600" />
                <span className="text-[9px] font-black text-emerald-600 uppercase tracking-widest">End-to-End Secure Merchant Onboarding</span>
            </div>
        </div>
    );
}
