'use client';

import { useEffect, useState } from 'react';
import Image from 'next/image';
import { Camera } from 'lucide-react';
import { useAuthStore } from '@/stores/authStore';
import { useUpdateProfile } from '@/hooks/useUpdateProfile';
import FileUpload from '@/components/Common/FileUpload';

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

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

  const [formData, setFormData] = useState({
    labName: '',
    email: '',
    contact: '',
    address: '',
    accreditation: '',
    licenceNumber: '',
    servicesOffered: '',
    specializations: '',
    location: '',
    established: '',
    avatar: '',
    userId: '',
    verificationDocuments: '',
  });

  const [avatarPreview, setAvatarPreview] = useState('/images/lab-avatar.jpg');
  const [isEditing, setIsEditing] = useState(false);
  const [successMsg, setSuccessMsg] = useState('');
  const [errorMsg, setErrorMsg] = useState('');

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

    const avatarUrl = user.avatar
      ? user.avatar.startsWith('https')
        ? user.avatar
        : `${process.env.NEXT_PUBLIC_BACKEND_URL}${user.avatar}`
      : '/images/lab-avatar.jpg';

    setFormData({
      labName: user.labName || '',
      email: user.email || '',
      contact: user.contact || '',
      address: user.address || '',
      accreditation: user.accreditation || '',
      licenceNumber: user.licenceNumber || '',
      servicesOffered: user.servicesOffered || '',
      specializations: user.specializations || '',
      location: user.location || '',
      established: user.established || '',
      avatar: user.avatar || '',
      userId: user.userId || '',
      verificationDocuments: user.verificationDocuments || '',
    });

    setAvatarPreview(avatarUrl);
  }, [user]);

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

  const handleAvatarChange = async (e) => {
    const file = e.target.files?.[0];
    if (!file || !user?.userId) return;

    const previewURL = URL.createObjectURL(file);
    setAvatarPreview(previewURL);

    const imageData = new FormData();
    imageData.append('avatar', file);
    imageData.append('userId', user.userId);

    try {
      const res = await fetch('/api/upload-avatar', {
        method: 'POST',
        body: imageData,
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.message || 'Upload failed');

      setFormData((prev) => ({ ...prev, avatar: data.avatarPath }));
      setSuccessMsg('Avatar uploaded!');
    } catch (err) {
      console.error('Avatar upload failed:', err);
      setErrorMsg('Failed to upload avatar');
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!user?.userId) {
      setErrorMsg('User not authenticated');
      return;
    }

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

  if (!user) return <p className="p-4 text-red-500">Unauthorized access</p>;

  return (
    <div className="p-4">
      <div className="mb-4 flex justify-between items-center">
        <h2 className="text-2xl font-bold">Lab Profile</h2>
        <button
          onClick={() => {
            setIsEditing(!isEditing);
            setSuccessMsg('');
            setErrorMsg('');
          }}
          className="bg-blue-600 text-white px-4 py-1 rounded-md hover:bg-blue-700"
          disabled={isLoading}
        >
          {isEditing ? 'Cancel' : 'Edit Profile'}
        </button>
      </div>

      {/* Avatar */}
      <div className="mb-6">
        <div className="relative w-32 h-32">
          <Image
            src={avatarPreview || '/images/lab-avatar.jpg'}
            alt="Lab Avatar"
            fill
            unoptimized
            className="rounded-full object-cover border-4 border-white shadow-lg"
          />
          {isEditing && (
            <label className="absolute bottom-0 right-0 bg-white p-1 rounded-full shadow cursor-pointer">
              <Camera className="w-5 h-5 text-gray-700" />
              <input
                type="file"
                accept="image/*"
                onChange={handleAvatarChange}
                className="hidden"
                disabled={isLoading}
              />
            </label>
          )}
        </div>
      </div>

      {/* Form */}
      <form onSubmit={handleSubmit} className="bg-white p-6 rounded-lg shadow-md w-full max-w-3xl space-y-4">
        <InputField label="Lab Name" name="labName" value={formData.labName} onChange={handleChange} disabled={!isEditing} required />
        <InputField label="Email" name="email" value={formData.email} onChange={handleChange} disabled />
        <InputField label="Contact" name="contact" value={formData.contact} onChange={handleChange} disabled={!isEditing} />
        <InputField label="Address" name="address" value={formData.address} onChange={handleChange} disabled={!isEditing} />
        <InputField label="Location" name="location" value={formData.location} onChange={handleChange} disabled={!isEditing} />
        <InputField label="Established" name="established" value={formData.established} onChange={handleChange} disabled={!isEditing} />
        <InputField label="Accreditation" name="accreditation" value={formData.accreditation} onChange={handleChange} disabled={!isEditing} />
        <InputField label="Licence Number" name="licenceNumber" value={formData.licenceNumber} onChange={handleChange} disabled={!isEditing} />
        <TextAreaField label="Services Offered" name="servicesOffered" value={formData.servicesOffered} onChange={handleChange} disabled={!isEditing} />
        <TextAreaField label="Specializations" name="specializations" value={formData.specializations} onChange={handleChange} disabled={!isEditing} />

        <FileUpload label="Verification Document" name="VerificationDocuments" value={formData.verificationDocuments} onChange={(url) => setFormData(prev => ({ ...prev, verificationDocuments: url }))} disabled={!isEditing} accept=".pdf,.doc,.docx" />

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

        {successMsg && <p className="text-green-600 text-sm mt-2">{successMsg}</p>}
        {errorMsg && <p className="text-red-600 text-sm mt-2">{errorMsg}</p>}
      </form>
    </div>
  );
}

// Reusable Input Component
function InputField({ label, name, value, onChange, disabled, required = false }) {
  return (
    <div>
      <label className="block text-sm font-medium">
        {label}
        {required && <span className="text-red-500"> *</span>}
      </label>
      <input
        type="text"
        name={name}
        value={value || ''}
        onChange={onChange}
        disabled={disabled}
        required={required && !disabled}
        className={`mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 ${disabled ? 'bg-gray-100' : ''}`}
      />
    </div>
  );
}

// Reusable TextArea Component
function TextAreaField({ label, name, value, onChange, disabled }) {
  return (
    <div>
      <label className="block text-sm font-medium">{label}</label>
      <textarea
        name={name}
        value={value || ''}
        onChange={onChange}
        disabled={disabled}
        rows={3}
        className={`mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 ${disabled ? 'bg-gray-100' : ''}`}
      />
    </div>
  );
}
