'use client';

import { useState, useEffect } from 'react';
import { useAuthStore } from '@/stores/authStore';
import Input from '@/components/Common/Input';
import Select from '@/components/Common/Select';
import AvatarUpload from '@/components/avatarUpload';
import { useUpdateProfile } from '@/hooks/useUpdateProfile';
import FileUpload from '@/components/Common/FileUpload';

export default function DoctorProfileEdit() {
    const userData = useAuthStore((state) => state.user);
    const user = userData?.profile || null;

    const { mutate: updateProfile, isLoading, isError, error } = useUpdateProfile();

    const [formData, setFormData] = useState({
        userId: '',
        uuid: '',
        role: '',
        firstName: '',
        lastName: '',
        avatar: '',
        phone: '',
        email: '',
        gender: '',
        dateOfBirth: '',
        licenceNumber: '',
        specialization: '',
        yearsOfExperience: '',
        education: '',
        hospitalAffiliation: '',
        address: '',
        bio: '',
        cvUrl: '',
        degreeCertificateUrl: '',
        backgroundCheckUrl: '',
        workReference: '',
        referenceName1: '',
        referenceEmail1: '',
        referenceHospital1: '',
        referencePhone1: '',
        referenceName2: '',
        referenceEmail2: '',
        referenceHospital2: '',
        referencePhone2: '',
        bankName: '',
        bankCode: '',
        accountName: '',
        accountNumber: '',
        accountType: '',
        bankCountry: '',
        swiftCode: '',

    });

    const [formErrors, setFormErrors] = useState({});
    const [isEditing, setIsEditing] = useState(false);
    const [loading, setLoading] = useState(false);
    const [successMsg, setSuccessMsg] = useState('');
    const [errorMsg, setErrorMsg] = useState('');

    const getAvatarUrl = (avatarPath) => {
        if (!avatarPath) return '/images/patient1.jpg';
        if (avatarPath.startsWith('https')) return avatarPath;
        return `${process.env.NEXT_PUBLIC_BACKEND_URL}${avatarPath}`;
    };

    useEffect(() => {
        if (!user) return;

        setFormData((prev) => ({
            ...prev,
            userId: user.userId || '',
            uuid: user.id || '',
            role: user.role || '',
            firstName: user.firstName || '',
            lastName: user.lastName || '',
            avatar: user.avatar || '',
            phone: user.phone || '',
            email: user.email || '',
            gender: user.gender || '',
            dateOfBirth: user.dateOfBirth?.slice(0, 10) || '',
            licenceNumber: user.licenceNumber || '',
            specialization: user.specialization || '',
            yearsOfExperience: user.yearsOfExperience || '',
            education: user.education || '',
            hospitalAffiliation: user.hospitalAffiliation || '',
            address: user.address || '',
            bio: user.bio || '',
            cvUrl: user.cvUrl || '',
            degreeCertificateUrl: user.degreeCertificateUrl || '',
            backgroundCheckUrl: user.backgroundCheckUrl || '',
            workReference: user.workReference || '',
            referenceName1: user.referenceName1 || '',
            referenceEmail1: user.referenceEmail1 || '',
            referenceHospital1: user.referenceHospital1 || '',
            referencePhone1: user.referencePhone1 || '',
            referenceName2: user.referenceName2 || '',
            referenceEmail2: user.referenceEmail2 || '',
            referenceHospital2: user.referenceHospital2 || '',
            referencePhone2: user.referencePhone2 || '',
            bankName: user.bankName || '',
            bankCode: user.bankCode || '',
            accountName: user.accountName || '',
            accountNumber: user.accountNumber || '',
            accountType: user.accountType || '',
            bankCountry: user.bankCountry || '',
            swiftCode: user.swiftCode || '',

        }));
    }, [user]);

    const validateForm = () => {
        const errors = {};
        const requiredFields = ['firstName', 'lastName', 'phone', 'email', 'gender', 'dateOfBirth', 'licenceNumber', 'address'];

        requiredFields.forEach(field => {
            if (!formData[field]?.trim()) {
                errors[field] = 'This field is required';
            }
        });

        if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
            errors.email = 'Please enter a valid email address';
        }

        setFormErrors(errors);
        return Object.keys(errors).length === 0;
    };

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData((prev) => ({ ...prev, [name]: value }));
        if (formErrors[name]) {
            setFormErrors(prev => ({ ...prev, [name]: '' }));
        }
    };

    const handleAvatarUpload = (newAvatar) => {
        setFormData(prev => ({ ...prev, avatar: newAvatar }));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!validateForm()) return;

        setLoading(true);
        setSuccessMsg('');
        setErrorMsg('');

        updateProfile(formData, {
            onSuccess: () => {
                setLoading(false);
                setIsEditing(false);
                setSuccessMsg('Profile updated successfully.');
            },
            onError: () => {
                setLoading(false);
                setErrorMsg('Update failed.');
            }
        });
    };

    return (
        <div className="p-4 bg-gray-50 min-h-screen">
            <div className="flex justify-between items-center mb-4">
                <h2 className="text-2xl font-bold text-gray-800">Doctor Profile</h2>
                <button
                    onClick={() => setIsEditing(prev => !prev)}
                    className="bg-blue-600 text-white px-4 py-1 rounded-md hover:bg-blue-700"
                >
                    {isEditing ? 'Cancel' : 'Edit Profile'}
                </button>
            </div>

            <div className="flex justify-center mb-6">
                <AvatarUpload
                    currentAvatar={getAvatarUrl(formData.avatar)}
                    onUpload={handleAvatarUpload}
                />
            </div>

            <form onSubmit={handleSubmit} className="space-y-6 bg-white p-6 rounded-xl shadow-md">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    <Input name="firstName" label="First Name" value={formData.firstName} onChange={handleChange} disabled={!isEditing} required error={formErrors.firstName} />
                    <Input name="lastName" label="Last Name" value={formData.lastName} onChange={handleChange} disabled={!isEditing} required error={formErrors.lastName} />
                    <Input name="phone" label="Phone" value={formData.phone} onChange={handleChange} disabled={!isEditing} required error={formErrors.phone} />
                    <Input name="email" label="Email" value={formData.email} onChange={handleChange} disabled={!isEditing} type="email" required error={formErrors.email} />
                    <Select name="gender" label="Gender" value={formData.gender} onChange={handleChange} disabled={!isEditing} options={['male', 'female']} required error={formErrors.gender} />
                    <Input name="dateOfBirth" label="Date of Birth" value={formData.dateOfBirth} onChange={handleChange} disabled={!isEditing} type="date" required error={formErrors.dateOfBirth} />
                    <Input name="licenceNumber" label="License Number" value={formData.licenceNumber} onChange={handleChange} disabled={!isEditing} required error={formErrors.licenceNumber} />
                    <Input name="address" label="Location" value={formData.address} onChange={handleChange} disabled={!isEditing} required error={formErrors.address} />
                    <Input name="yearsOfExperience" label="Years of Experience" value={formData.yearsOfExperience} onChange={handleChange} disabled={!isEditing} type="number" min="0" max="50" />
                </div>

                {/* Textarea Fields */}
                <div className="border-t pt-4 mt-6 space-y-6">
                    <div>
                        <h4 className="text-lg font-semibold mb-1">Specialization</h4>
                        <textarea name="specialization" value={formData.specialization} onChange={handleChange} disabled={!isEditing} className="w-full p-2 border rounded-md h-24" />
                    </div>

                    <div>
                        <h4 className="text-lg font-semibold mb-1">Bio</h4>
                        <textarea name="bio" value={formData.bio} onChange={handleChange} disabled={!isEditing} className="w-full p-2 border rounded-md h-24" />
                    </div>

                    <div>
                        <h4 className="text-lg font-semibold mb-1">Education</h4>
                        <textarea name="education" value={formData.education} onChange={handleChange} disabled={!isEditing} className="w-full p-2 border rounded-md h-24" />
                    </div>

                    <div>
                        <h4 className="text-lg font-semibold mb-1">Hospital Affiliation</h4>
                        <textarea name="hospitalAffiliation" value={formData.hospitalAffiliation} onChange={handleChange} disabled={!isEditing} className="w-full p-2 border rounded-md h-24" />
                    </div>
                </div>

                {/* Reference 1 */}
                <div className="border-t pt-4 mt-6">
                    <h4 className="text-lg font-semibold mb-2">Reference Contact 1</h4>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        <Input name="referenceName1" label="Name" value={formData.referenceName1} onChange={handleChange} disabled={!isEditing} />
                        <Input name="referenceEmail1" label="Email" value={formData.referenceEmail1} onChange={handleChange} disabled={!isEditing} />
                        <Input name="referenceHospital1" label="Hospital" value={formData.referenceHospital1} onChange={handleChange} disabled={!isEditing} />
                        <Input name="referencePhone1" label="Phone" value={formData.referencePhone1} onChange={handleChange} disabled={!isEditing} />
                    </div>
                </div>

                {/* Reference 2 */}
                <div className="border-t pt-4 mt-6">
                    <h4 className="text-lg font-semibold mb-2">Reference Contact 2</h4>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        <Input name="referenceName2" label="Name" value={formData.referenceName2} onChange={handleChange} disabled={!isEditing} />
                        <Input name="referenceEmail2" label="Email" value={formData.referenceEmail2} onChange={handleChange} disabled={!isEditing} />
                        <Input name="referenceHospital2" label="Hospital" value={formData.referenceHospital2} onChange={handleChange} disabled={!isEditing} />
                        <Input name="referencePhone2" label="Phone" value={formData.referencePhone2} onChange={handleChange} disabled={!isEditing} />
                    </div>
                </div>

                {/* Bank Details */}
                <div className="border-t pt-4 mt-6">
                    <h4 className="text-lg font-semibold mb-2">Bank Payment Details</h4>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        <Input name="bankName" label="Bank Name" value={formData.bankName} onChange={handleChange} disabled={!isEditing} />
                        <Input name="bankCode" label="Bank Code / Routing Number" value={formData.bankCode} onChange={handleChange} disabled={!isEditing} />
                        <Input name="accountName" label="Account Name" value={formData.accountName} onChange={handleChange} disabled={!isEditing} />
                        <Input name="accountNumber" label="Account Number" value={formData.accountNumber} onChange={handleChange} disabled={!isEditing} />
                        <Input name="accountType" label="Account Type (e.g. savings)" value={formData.accountType} onChange={handleChange} disabled={!isEditing} />
                        <Input name="bankCountry" label="Bank Country" value={formData.bankCountry} onChange={handleChange} disabled={!isEditing} />
                        <Input name="swiftCode" label="SWIFT Code" value={formData.swiftCode} onChange={handleChange} disabled={!isEditing} />
                    </div>
                </div>

                {/* File Uploads */}
                <div className="border-t pt-4 mt-6 grid grid-cols-1 md:grid-cols-2 gap-4">
                    <FileUpload label="Curriculum Vitae (CV)" name="cvUrl" value={formData.cvUrl} onChange={(url) => setFormData(prev => ({ ...prev, cvUrl: url }))} disabled={!isEditing} accept=".pdf,.doc,.docx" />
                    <FileUpload label="Degree Certificate" name="degreeCertificateUrl" value={formData.degreeCertificateUrl} onChange={(url) => setFormData(prev => ({ ...prev, degreeCertificateUrl: url }))} disabled={!isEditing} accept=".pdf,.jpg,.jpeg,.png" />
                    <FileUpload label="Police Clearance / Background Check" name="backgroundCheckUrl" value={formData.backgroundCheckUrl} onChange={(url) => setFormData(prev => ({ ...prev, backgroundCheckUrl: url }))} disabled={!isEditing} accept=".pdf,.jpg,.jpeg,.png" />
                    <FileUpload label="Work Reference" name="workReference" value={formData.workReference} onChange={(url) => setFormData(prev => ({ ...prev, workReference: url }))} disabled={!isEditing} accept=".pdf,.doc,.docx" />
                </div>

                {/* Uploaded status */}
                {formData.cvUrl && formData.degreeCertificateUrl && formData.backgroundCheckUrl && (
                    <div className="bg-blue-50 p-4 rounded-md mt-4">
                        <p className="text-blue-800">Your documents have been uploaded and are pending verification by our team.</p>
                    </div>
                )}

                {/* Status Messages */}
                {successMsg && <p className="text-green-600">{successMsg}</p>}
                {errorMsg && <p className="text-red-600">{errorMsg}</p>}

                {/* Submit */}
                {isEditing && (
                    <button
                        type="submit"
                        className="bg-green-600 text-white px-6 py-2 rounded-md hover:bg-green-700"
                        disabled={loading}
                    >
                        {loading ? 'Saving...' : 'Save Changes'}
                    </button>
                )}
            </form>
        </div>
    );
}