'use client';
import { useAuth } from '../../../lib/authContext';
import EmployeeLayout from '../../../components/EmployeeLayout';
import { useState, useEffect } from 'react';

export default function EmployeeProfilePage() {
  const { user, isLoading } = useAuth();
  const [editing, setEditing] = useState(false);
  const [loading, setLoading] = useState(true);
  const [employeeDetails, setEmployeeDetails] = useState<any>(null);
  const [formData, setFormData] = useState({
    phone: '',
    dob: '',
    physicalAddress: '',
    emergencyContactName: '',
    bloodGroup: '',
    nationalId: '',
    kraPin: '',
    directSupervisor: '',
  });
  const [saving, setSaving] = useState(false);
  const [toast, setToast] = useState({ message: '', type: '' });

  useEffect(() => {
    if (user?.employeeId) {
      fetchEmployeeDetails();
    }
  }, [user]);

  const fetchEmployeeDetails = async () => {
    try {
      const response = await fetch(`/api/employee/profile?employeeId=${user?.employeeId}`);
      if (response.ok) {
        const data = await response.json();
        setEmployeeDetails(data);
        setFormData({
          phone: data.phone || '',
          dob: data.dob ? data.dob.split('T')[0] : '',
          physicalAddress: data.physicalAddress || data.address || '',
          emergencyContactName: data.emergencyContactName || data.emergencyContact || '',
          bloodGroup: data.bloodGroup || '',
          nationalId: data.nationalId || '',
          kraPin: data.kraPin || '',
          directSupervisor: data.directSupervisor || '',
        });
      }
    } catch (error) {
      console.error('Error fetching employee details:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const response = await fetch('/api/employee/profile', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          employeeId: user?.employeeId,
          email: user?.email,
          phone: formData.phone,
          dob: formData.dob,
          physicalAddress: formData.physicalAddress,
          emergencyContactName: formData.emergencyContactName,
          bloodGroup: formData.bloodGroup,
          nationalId: formData.nationalId,
          kraPin: formData.kraPin,
          directSupervisor: formData.directSupervisor,
        }),
      });
      
      const data = await response.json();
      
      if (response.ok) {
        setEditing(false);
        fetchEmployeeDetails();
        setToast({ message: 'Profile updated successfully!', type: 'success' });
        setTimeout(() => setToast({ message: '', type: '' }), 3000);
      } else {
        throw new Error(data.error || 'Failed to update');
      }
    } catch (error) {
      console.error('Update error:', error);
      setToast({ message: error instanceof Error ? error.message : 'Failed to update profile', type: 'error' });
      setTimeout(() => setToast({ message: '', type: '' }), 3000);
    } finally {
      setSaving(false);
    }
  };

  if (isLoading || loading) {
    return (
      <EmployeeLayout title="My Profile">
        <div className="flex items-center justify-center h-64">
          <div className="text-center">
            <div className="w-12 h-12 border-4 border-purple-600 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
            <p className="text-gray-500">Loading profile...</p>
          </div>
        </div>
      </EmployeeLayout>
    );
  }

  if (!user) return null;

  const details = employeeDetails || {};
  const role = user?.position || details.position || 'Employee';
  const department = user?.dept || details.dept || 'Not Assigned';

  const infoFields = [
    { label: 'Full Name', value: user?.name || '-', icon: 'ri-user-line', editable: false },
    { label: 'Employee ID', value: user?.employeeId || '-', icon: 'ri-id-card-line', editable: false },
    { label: 'Department', value: department, icon: 'ri-building-line', editable: false },
    { label: 'Job Title', value: role, icon: 'ri-briefcase-line', editable: false },
    { label: 'Email Address', value: user?.email || '-', icon: 'ri-mail-line', editable: false },
    { label: 'Phone Number', value: details.phone || '-', icon: 'ri-phone-line', editable: true },
    { label: 'Date of Birth', value: details.dob ? new Date(details.dob).toLocaleDateString() : '-', icon: 'ri-cake-line', editable: true },
    { label: 'Gender', value: details.gender || '-', icon: 'ri-user-smile-line', editable: false },
    { label: 'Employment Type', value: details.employmentType || 'Permanent', icon: 'ri-contract-line', editable: false },
    { label: 'Date Joined', value: details.joinDate ? new Date(details.joinDate).toLocaleDateString() : '-', icon: 'ri-calendar-line', editable: false },
    { label: 'National ID', value: details.nationalId || '-', icon: 'ri-file-text-line', editable: true },
    { label: 'KRA PIN', value: details.kraPin || '-', icon: 'ri-government-line', editable: true },
    { label: 'Direct Supervisor', value: details.directSupervisor || '-', icon: 'ri-user-star-line', editable: true },
    { label: 'Physical Address', value: details.physicalAddress || '-', icon: 'ri-map-pin-line', editable: true },
    { label: 'Emergency Contact', value: details.emergencyContactName || '-', icon: 'ri-user-heart-line', editable: true },
    { label: 'Blood Group', value: details.bloodGroup || '-', icon: 'ri-drop-line', editable: true },
  ];

  return (
    <EmployeeLayout title="My Profile">
      {toast.message && (
        <div className={`fixed top-20 right-6 z-[100] text-white px-5 py-3 rounded-xl shadow-lg text-sm font-medium ${toast.type === 'success' ? 'bg-green-600' : 'bg-red-600'}`}>
          {toast.message}
        </div>
      )}

      <div className="max-w-4xl mx-auto">
        {/* Profile Header */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6">
          <div className="h-24 w-full" style={{ background: '#b22698' }}></div>
          <div className="px-6 pb-6">
            <div className="flex items-end gap-4 -mt-10 mb-4 flex-wrap">
              <div className="w-20 h-20 rounded-2xl flex items-center justify-center text-white font-bold text-2xl border-4 border-white shadow-md" style={{ background: '#b828a0' }}>
                {user?.name?.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2)}
              </div>
              <div className="pb-1">
                <h2 className="text-xl font-bold text-gray-800">{user?.name}</h2>
                <p className="text-gray-500 text-sm">{role} · {department}</p>
              </div>
              <div className="ml-auto pb-1 flex gap-2">
                <span className="bg-green-100 text-green-700 text-xs font-semibold px-3 py-1.5 rounded-full">
                  {user?.isActive ? 'Active' : 'Inactive'}
                </span>
                <button
                  onClick={() => setEditing(!editing)}
                  className="px-4 py-1.5 rounded-lg text-sm font-medium text-white transition-colors"
                  style={{ background: '#b828a0' }}
                >
                  {editing ? 'Cancel' : 'Edit Profile'}
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Profile Details */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <h3 className="font-semibold text-gray-800 mb-5">Personal & Employment Details</h3>
          
          {editing ? (
            <div className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Phone Number</label>
                  <input type="tel" value={formData.phone} onChange={(e) => setFormData({ ...formData, phone: e.target.value })} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-purple-500" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Date of Birth</label>
                  <input type="date" value={formData.dob} onChange={(e) => setFormData({ ...formData, dob: e.target.value })} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-purple-500" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">National ID</label>
                  <input type="text" value={formData.nationalId} onChange={(e) => setFormData({ ...formData, nationalId: e.target.value })} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm" placeholder="National ID number" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">KRA PIN</label>
                  <input type="text" value={formData.kraPin} onChange={(e) => setFormData({ ...formData, kraPin: e.target.value })} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm" placeholder="KRA PIN" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Direct Supervisor</label>
                  <input type="text" value={formData.directSupervisor} onChange={(e) => setFormData({ ...formData, directSupervisor: e.target.value })} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm" placeholder="Supervisor name" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Physical Address</label>
                  <input type="text" value={formData.physicalAddress} onChange={(e) => setFormData({ ...formData, physicalAddress: e.target.value })} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm" placeholder="Your address" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Emergency Contact Name</label>
                  <input type="text" value={formData.emergencyContactName} onChange={(e) => setFormData({ ...formData, emergencyContactName: e.target.value })} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm" placeholder="Emergency contact person" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Blood Group</label>
                  <select value={formData.bloodGroup} onChange={(e) => setFormData({ ...formData, bloodGroup: e.target.value })} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm">
                    <option value="">Select Blood Group</option>
                    <option value="A+">A+</option>
                    <option value="A-">A-</option>
                    <option value="B+">B+</option>
                    <option value="B-">B-</option>
                    <option value="O+">O+</option>
                    <option value="O-">O-</option>
                    <option value="AB+">AB+</option>
                    <option value="AB-">AB-</option>
                  </select>
                </div>
              </div>
              <div className="flex gap-3 pt-4">
                <button onClick={handleSave} disabled={saving} className="px-4 py-2 rounded-lg text-sm font-medium text-white transition-colors disabled:opacity-50" style={{ background: '#b828a0' }}>
                  {saving ? 'Saving...' : 'Save Changes'}
                </button>
                <button onClick={() => setEditing(false)} className="px-4 py-2 border border-gray-200 rounded-lg text-sm font-medium text-gray-600 hover:bg-gray-50">
                  Cancel
                </button>
              </div>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {infoFields.map((field, i) => (
                <div key={i} className="flex items-start gap-3 p-3 bg-gray-50 rounded-xl">
                  <div className="w-8 h-8 flex items-center justify-center rounded-lg mt-0.5" style={{ background: '#fdf2fb' }}>
                    <i className={`${field.icon} text-sm`} style={{ color: '#b828a0' }}></i>
                  </div>
                  <div>
                    <p className="text-xs text-gray-400 font-medium">{field.label}</p>
                    <p className="text-sm font-semibold text-gray-700 mt-0.5">{field.value}</p>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </EmployeeLayout>
  );
}