import React, { useState } from 'react';
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, usePage, useForm, router } from '@inertiajs/react';
import { PageProps } from '@/types';
import swal from '@/lib/swal';

// FilePond
import { FilePond, registerPlugin } from 'react-filepond';
import 'filepond/dist/filepond.min.css';
import FilePondPluginImagePreview from 'filepond-plugin-image-preview';
import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css';
import FilePondPluginFileValidateType from 'filepond-plugin-file-validate-type';

registerPlugin(FilePondPluginImagePreview, FilePondPluginFileValidateType);

interface ProfileEditProps extends PageProps {
    mustVerifyEmail: boolean;
    status?: string;
}

function SectionCard({ title, description, children, delay = '0s' }: { title: string; description: string; children: React.ReactNode; delay?: string }) {
    return (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden h-full flex flex-col anim-up" style={{ animationDelay: delay }}>
            <div className="px-6 py-4 border-b border-gray-50 bg-gray-50/30">
                <h2 className="text-sm font-bold text-[#3D4E4B] tracking-tight">{title}</h2>
                <p className="text-xs text-gray-400 font-semibold tracking-tight mt-1">{description}</p>
            </div>
            <div className="p-6 flex-1">{children}</div>
        </div>
    );
}

function InputField({ label, id, type = 'text', value, onChange, error, placeholder, required = false, ...props }: any) {
    return (
        <div className="space-y-1.5">
            <label htmlFor={id} className="block text-xs font-bold text-gray-400 tracking-tight ml-1">{label} {required && <span className="text-red-500">*</span>}</label>
            <input
                id={id} type={type} value={value} onChange={onChange} placeholder={placeholder}
                className={`w-full px-4 py-2.5 rounded-xl border text-sm font-bold transition-all outline-none
                    ${error ? 'border-red-300 bg-red-50' : 'border-gray-100 bg-gray-50/30 focus:border-[#D4A017] focus:bg-white'}`}
                {...props}
            />
            {error && <p className="text-sm text-red-500 font-bold ml-1">{error}</p>}
        </div>
    );
}

export default function ProfileEdit({ mustVerifyEmail, status }: ProfileEditProps) {
    const { auth } = usePage<PageProps>().props;
    const { user } = auth;

    const [files, setFiles] = useState<any[]>([]);

    const profileForm = useForm({
        first_name: user.first_name || '',
        last_name: user.last_name || '',
        email: user.email || '',
        phone: user.phone || '',
        bio: user.bio || '',
        avatar_file: null as File | null,
        _method: 'PATCH'
    });

    const passwordForm = useForm({
        current_password: '',
        password: '',
        password_confirmation: '',
    });

    const handleProfileSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        profileForm.post(route('profile.update'), {
            preserveScroll: true,
            onSuccess: () => swal.success('Success', 'Profile identity synchronized.'),
        });
    };

    const handlePasswordSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        passwordForm.put(route('password.update'), {
            preserveScroll: true,
            onSuccess: () => {
                passwordForm.reset();
                swal.success('Success', 'Security token updated.');
            },
        });
    };

    const initials = `${user.first_name?.charAt(0) || ''}${user.last_name?.charAt(0) || ''}`.toUpperCase();

    return (
        <AuthenticatedLayout>
            <Head title="Account Settings" />

            <div className="mb-6 anim-down">
                <h1 className="text-lg font-bold text-[#3D4E4B] dark:text-white tracking-tight leading-none">Account Settings</h1>
                <p className="text-xs font-semibold text-gray-400 tracking-tight mt-2">Personal Identity & Security Governance</p>
            </div>

            {/* Grid 6 6 Layout for Precision - Enforcing full-width grid-cols-2 */}
            <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-6 pb-20">
                
                {/* Column 1: Identity Configuration */}
                <div className="space-y-6">
                    <SectionCard title="Identity Configuration" description="Manage your personal credentials" delay="0s">
                        <form onSubmit={handleProfileSubmit} className="space-y-6">
                            <div className="flex flex-col sm:flex-row items-center gap-6 mb-4">
                                <div className={`w-24 h-24 rounded-2xl flex items-center justify-center text-white text-3xl font-bold shrink-0 border border-gray-100 dark:border-white/5 ${!user.avatar_url ? 'bg-[#3D4E4B]' : 'bg-white dark:bg-white/5'}`}>
                                    {user.avatar_url ? (
                                        <img src={user.avatar_url} className="w-full h-full object-cover rounded-2xl" />
                                    ) : initials}
                                </div>
                                <div className="flex-1 w-full">
                                    <label className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-2 block">Identity Portrait</label>
                                    <FilePond files={files} onupdatefiles={items => {
                                        setFiles(items);
                                        profileForm.setData('avatar_file', items[0]?.file as File || null);
                                    }} allowMultiple={false} maxFiles={1} labelIdle='Portrait update' />
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <InputField label="First Designation" id="first_name" value={profileForm.data.first_name}
                                    onChange={(e: any) => profileForm.setData('first_name', e.target.value)}
                                    error={profileForm.errors.first_name} required placeholder="e.g. Alex" />
                                <InputField label="Last Designation" id="last_name" value={profileForm.data.last_name}
                                    onChange={(e: any) => profileForm.setData('last_name', e.target.value)}
                                    error={profileForm.errors.last_name} required placeholder="e.g. Johnson" />
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <InputField label="Communication Channel (Email)" id="email" type="email" value={profileForm.data.email}
                                    onChange={(e: any) => profileForm.setData('email', e.target.value)}
                                    error={profileForm.errors.email} required placeholder="alex@company.com" />
                                <InputField label="Contact Number (Phone)" id="phone" type="tel" value={profileForm.data.phone}
                                    onChange={(e: any) => profileForm.setData('phone', e.target.value)}
                                    error={profileForm.errors.phone} placeholder="+62..." />
                            </div>

                            <div className="space-y-1.5">
                                <label className="block text-[10px] font-black text-gray-400 uppercase tracking-widest ml-1">Professional Bio</label>
                                <textarea 
                                    value={profileForm.data.bio} 
                                    onChange={e => profileForm.setData('bio', e.target.value)}
                                    rows={4}
                                    className="input-field py-3 resize-none"
                                    placeholder="Tell us about yourself..."
                                />
                            </div>

                            <div className="flex justify-end pt-2">
                                <button type="submit" disabled={profileForm.processing}
                                    className="px-8 py-3 bg-[#3D4E4B] text-white text-sm font-bold tracking-tight rounded-xl hover:bg-[#2D3A38] transition-all shadow-lg shadow-[#3D4E4B]/20">
                                    {profileForm.processing ? 'Synchronizing...' : 'Update Identity'}
                                </button>
                            </div>
                        </form>
                    </SectionCard>
                </div>

                {/* Column 2: Security & Liquidation */}
                <div className="space-y-6 flex flex-col">
                    <SectionCard title="Security Protocols" description="Authentication & Token Lifecycle" delay="0.1s">
                        <form onSubmit={handlePasswordSubmit} className="space-y-4">
                            <InputField label="Current Security Token" id="current_password" type="password"
                                value={passwordForm.data.current_password}
                                onChange={(e: any) => passwordForm.setData('current_password', e.target.value)}
                                error={passwordForm.errors.current_password} required placeholder="••••••••" />
                            <InputField label="New Security Token" id="password" type="password"
                                value={passwordForm.data.password}
                                onChange={(e: any) => passwordForm.setData('password', e.target.value)}
                                error={passwordForm.errors.password} required placeholder="••••••••" />
                            <InputField label="Verify Token" id="password_confirmation" type="password"
                                value={passwordForm.data.password_confirmation}
                                onChange={(e: any) => passwordForm.setData('password_confirmation', e.target.value)}
                                error={(passwordForm.errors as any).password_confirmation} required placeholder="••••••••" />

                            <div className="pt-4">
                                <button type="submit" disabled={passwordForm.processing}
                                    className="w-full py-3 bg-[#D4A017] text-white text-sm font-bold tracking-tight rounded-xl hover:bg-[#B88B14] transition-all">
                                    {passwordForm.processing ? '...' : 'Rotate Security Tokens'}
                                </button>
                            </div>
                        </form>
                    </SectionCard>

                    <div className="bg-white rounded-2xl border border-red-100 p-6 shadow-sm anim-up" style={{ animationDelay: '0.2s' }}>
                        <div className="flex items-center justify-between mb-4">
                            <h3 className="text-sm font-bold text-red-800 tracking-tight">Termination Zone</h3>
                            <span className="px-2 py-0.5 bg-red-50 text-red-600 text-sm font-bold rounded-md border border-red-100">Critical</span>
                        </div>
                        <p className="text-xs text-red-600 font-semibold leading-relaxed mb-4">Once account liquidation is initiated, the process is irreversible. All associated data assets will be purged.</p>
                        <button onClick={() => {
                            swal.confirmDelete('Your Entire Account').then(r => {
                                if(r.isConfirmed) router.delete(route('profile.destroy'));
                            });
                        }} className="w-full py-3 border border-red-100 text-red-600 text-xs font-bold tracking-tight rounded-xl hover:bg-red-50 transition-colors">
                            Initiate Liquidation
                        </button>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
