'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';

export default function PatientProfileEdit() {
    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: '',
        avatar: '',
        middleName: '',
        lastName: '',
        phone: '',
        email: '',
        gender: '',
        dateOfBirth: '',
        bloodType: '',
        height: '',
        weight: '',
        address: '',
        allergies: '',
        medicalHistory: '',
        emergencyContactName: '',
        emergencyContactRelationship: '',
        emergencyContactPhone: '',
        insuranceProvider: '',
        insuranceNumber: '',
        socialHistory: {
            smoking: false,
            alcohol: false,
            drugs: false,
        },
    });

    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({
            userId: user.userId || '',
            uuid: user.id || '',
            role: user.role || '',
            firstName: user.firstName || '',
            middleName: user.middleName || '',
            lastName: user.lastName || '',
            avatar: user.avatar || '',
            phone: user.phone || '',
            email: user.email || '',
            gender: user.gender || '',
            dateOfBirth: user.dateOfBirth?.slice(0, 10) || '',
            bloodType: user.bloodType || '',
            height: user.height || '',
            weight: user.weight || '',
            address: user.address || '',
            allergies: user.allergies || '',
            medicalHistory: user.medicalHistory || '',
            emergencyContactName: user.emergencyContactName || '',
            emergencyContactRelationship: user.emergencyContactRelationship || '',
            emergencyContactPhone: user.emergencyContactPhone || '',
            insuranceProvider: user.insuranceProvider || '',
            insuranceNumber: user.insuranceNumber || '',
            socialHistory: {
                smoking: user.socialHistory?.smoking || false,
                alcohol: user.socialHistory?.alcohol || false,
                drugs: user.socialHistory?.drugs || false,
            },
        });
    }, [user]);

    const handleChange = (e) => {
        const { name, value, type, checked } = e.target;
        if (name in formData.socialHistory) {
            setFormData((prev) => ({
                ...prev,
                socialHistory: {
                    ...prev.socialHistory,
                    [name]: type === 'checkbox' ? checked : value,
                },
            }));
        } else {
            setFormData((prev) => ({ ...prev, [name]: value }));
        }
    };

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

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        setSuccessMsg('');
        setErrorMsg('');

        updateProfile(formData, {
            onSuccess: () => {
                setLoading(false);
                setIsEditing(false);
                setSuccessMsg('Profile updated successfully.');
            },
            onError: () => {
                setLoading(false);
                setErrorMsg('Failed to update profile.');
            }
        });
    };

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

            {loading && (
                <div className="mb-4 text-blue-600 font-medium">Updating profile...</div>
            )}
            {successMsg && (
                <div className="mb-4 text-green-600 bg-green-100 border border-green-300 px-4 py-2 rounded-md">
                    {successMsg}
                </div>
            )}
            {errorMsg && (
                <div className="mb-4 text-red-600 bg-red-100 border border-red-300 px-4 py-2 rounded-md">
                    {errorMsg}
                </div>
            )}

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

            <form
                onSubmit={handleSubmit}
                className="bg-white rounded-xl shadow-md p-6 space-y-6"
            >
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 text-sm">
                    <Input label="First Name" name="firstName" value={formData.firstName} onChange={handleChange} disabled={!isEditing || loading} required />
                    <Input label="Middle Name" name="middleName" value={formData.middleName} onChange={handleChange} disabled={!isEditing || loading} required />
                    <Input label="Last Name" name="lastName" value={formData.lastName} onChange={handleChange} disabled={!isEditing || loading} required />
                    <Input label="Mobile" name="phone" value={formData.phone} onChange={handleChange} disabled={!isEditing || loading} required />
                    <Input label="Email" name="email" value={formData.email} onChange={handleChange} disabled required />
                    <Select label="Gender" name="gender" value={formData.gender} onChange={handleChange} disabled={!isEditing || loading} options={['male', 'female', 'Other']} required />
                    <Input label="Date of Birth" type="date" name="dateOfBirth" value={formData.dateOfBirth} onChange={handleChange} disabled={!isEditing || loading} required />
                    <Select label="Blood Type" name="bloodType" value={formData.bloodType} onChange={handleChange} disabled={!isEditing || loading} options={['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-']} required />
                    <Input label="Height (cm)" name="height" value={formData.height} onChange={handleChange} disabled={!isEditing || loading} required />
                    <Input label="Weight (kg)" name="weight" value={formData.weight} onChange={handleChange} disabled={!isEditing || loading} required />
                    <Input label="Address" name="address" value={formData.address} onChange={handleChange} disabled={!isEditing || loading} required />

                    {/* Hidden inputs */}
                    <Input type="hidden" name="userId" value={formData.userId} />
                    <Input type="hidden" name="role" value="patient" />
                    <Input type="hidden" name="uuid" value={formData.uuid} />

                    {/* Allergies */}
                    <div className="col-span-1 md:col-span-2 lg:col-span-3">
                        <label className="block mb-1 text-sm font-medium text-gray-700">Allergies</label>
                        <textarea name="allergies" value={formData.allergies} onChange={handleChange} disabled={!isEditing || loading} rows={3} className="w-full border rounded-md px-3 py-2 text-sm bg-white" placeholder="E.g., Penicillin, peanuts..." />
                    </div>

                    {/* Medical History */}
                    <div className="col-span-1 md:col-span-2 lg:col-span-3">
                        <label className="block mb-1 text-sm font-medium text-gray-700">Medical History</label>
                        <textarea name="medicalHistory" value={formData.medicalHistory} onChange={handleChange} disabled={!isEditing || loading} rows={3} className="w-full border rounded-md px-3 py-2 text-sm bg-white" placeholder="E.g., Diabetes, surgeries..." />
                    </div>

                    {/* Emergency Contact */}
                    <div className="col-span-1 md:col-span-2 lg:col-span-3">
                        <h3 className="font-semibold text-gray-800 mb-2">Emergency Contact</h3>
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <Input label="Name" name="emergencyContactName" value={formData.emergencyContactName} onChange={handleChange} disabled={!isEditing || loading} required />
                            <Input label="Relationship" name="emergencyContactRelationship" value={formData.emergencyContactRelationship} onChange={handleChange} disabled={!isEditing || loading} required />
                            <Input label="Phone" name="emergencyContactPhone" value={formData.emergencyContactPhone} onChange={handleChange} disabled={!isEditing || loading} required />
                        </div>
                    </div>

                    {/* Insurance Info */}
                    <div className="col-span-1 md:col-span-2 lg:col-span-3">
                        <h3 className="font-semibold text-gray-800 mb-2">Insurance</h3>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <Input label="Provider" name="insuranceProvider" value={formData.insuranceProvider} onChange={handleChange} disabled={!isEditing || loading} required />
                            <Input label="Policy Number" name="insuranceNumber" value={formData.insuranceNumber} onChange={handleChange} disabled={!isEditing || loading} required />
                        </div>
                    </div>

                    {/* Social History */}
                    <div className="col-span-1 md:col-span-2 lg:col-span-3">
                        <h3 className="font-semibold text-gray-800 mb-2">Social History</h3>
                        <div className="flex flex-wrap gap-6 text-sm">
                            <label className="flex items-center space-x-2">
                                <input type="checkbox" name="smoking" checked={formData.socialHistory.smoking} onChange={handleChange} disabled={!isEditing || loading} />
                                <span>Smoking</span>
                            </label>
                            <label className="flex items-center space-x-2">
                                <input type="checkbox" name="alcohol" checked={formData.socialHistory.alcohol} onChange={handleChange} disabled={!isEditing || loading} />
                                <span>Alcohol</span>
                            </label>
                            <label className="flex items-center space-x-2">
                                <input type="checkbox" name="drugs" checked={formData.socialHistory.drugs} onChange={handleChange} disabled={!isEditing || loading} />
                                <span>Recreational Drugs</span>
                            </label>
                        </div>
                    </div>
                </div>

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