import React, { useState, useEffect } from 'react';
import { Edit, Phone, Mail, MapPin, Shield, Save, X, AlertCircle, CheckCircle } from 'lucide-react';
import { useAuth } from '../context/AuthContext';
import { useApp } from '../context/AppContext';
import { organizationalApi, departmentsApi, designationsApi, ranksApi, authApi } from '../services/api';

const Profile: React.FC = () => {
  const { user: authUser } = useAuth();
  const { users } = useApp();
  
  // Find full user details
  const user = users.find(u => u.id === authUser?.id) || users[0];

  // Form state
  const [isEditing, setIsEditing] = useState(false);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  
  // Dropdown data
  const [ranks, setRanks] = useState<Array<{id: number; name: string}>>([]);
  const [units, setUnits] = useState<Array<{id: number; name: string}>>([]);
  const [departments, setDepartments] = useState<Array<{id: number; name: string}>>([]);
  const [designations, setDesignations] = useState<Array<{id: number; name: string}>>([]);
  const [dataLoading, setDataLoading] = useState(false);

  // Form data following API structure
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    service_no: '',
    mobile: '',
    rank_id: null as number | null,
    unit_id: null as number | null,
    department_id: null as number | null,
    designation_id: null as number | null,
  });

  // Initialize form data when user changes
  useEffect(() => {
    if (user) {
      setFormData({
        name: user.name || '',
        email: user.email || '',
        service_no: user.service_no || '',
        mobile: user.mobile || '',
        rank_id: null, // Will be set from dropdown selection
        unit_id: null, // Will be set from dropdown selection
        department_id: null, // Will be set from dropdown selection
        designation_id: null, // Will be set from dropdown selection
      });
    }
  }, [user]);

  // Load dropdown data
  const loadDropdownData = async () => {
    setDataLoading(true);
    try {
      const [ranksResponse, unitsResponse, departmentsResponse, designationsResponse] = await Promise.all([
        ranksApi.getRanksForDropdown(),
        organizationalApi.getUnits({ tree: false }),
        departmentsApi.getDepartmentsForDropdown(),
        designationsApi.getDesignationsForDropdown()
      ]);

      if (ranksResponse.status === 'success' && ranksResponse.data) {
        setRanks(ranksResponse.data);
      }
      if (unitsResponse.status === 'success' && unitsResponse.data) {
        setUnits(unitsResponse.data.units.sort((a: {id: number}, b: {id: number}) => a.id - b.id));
      }
      if (departmentsResponse.status === 'success' && departmentsResponse.data) {
        setDepartments(departmentsResponse.data);
      }
      if (designationsResponse.status === 'success' && designationsResponse.data) {
        setDesignations(designationsResponse.data);
      }
    } catch (error) {
      console.error('Failed to load dropdown data:', error);
    } finally {
      setDataLoading(false);
    }
  };

  // Load dropdown data when editing starts
  useEffect(() => {
    if (isEditing) {
      loadDropdownData();
    }
  }, [isEditing]);

  // Handle form input changes
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: name.includes('_id') ? (value === '' ? null : parseInt(value)) : value
    }));
  };

  // Handle form submission
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage(null);

    try {
      // Validate required fields
      if (!formData.name || !formData.email || !formData.service_no) {
        setMessage({ type: 'error', text: 'Please fill in all required fields' });
        setLoading(false);
        return;
      }

      if (!formData.rank_id || !formData.unit_id || !formData.department_id || !formData.designation_id) {
        setMessage({ type: 'error', text: 'Please select all required dropdown options' });
        setLoading(false);
        return;
      }

      // Call the updateProfile API
      const response = await authApi.updateProfile({
        name: formData.name,
        email: formData.email,
        service_no: formData.service_no,
        rank_id: formData.rank_id,
        unit_id: formData.unit_id,
        department_id: formData.department_id,
        designation_id: formData.designation_id,
      });

      if (response.status === 'success') {
        setMessage({ type: 'success', text: 'Profile updated successfully!' });
        setIsEditing(false);
        // Profile updated successfully - no need to reload page
      } else {
        setMessage({ type: 'error', text: response.message || 'Failed to update profile' });
      }
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : 'Failed to update profile';
      setMessage({ type: 'error', text: errorMessage });
    } finally {
      setLoading(false);
    }
  };

  // Handle cancel edit
  const handleCancel = () => {
    setIsEditing(false);
    setMessage(null);
    // Reset form data to original values
    if (user) {
      setFormData({
        name: user.name || '',
        email: user.email || '',
        service_no: user.service_no || '',
        mobile: user.mobile || '',
        rank_id: null, // Will be set from dropdown selection
        unit_id: null, // Will be set from dropdown selection
        department_id: null, // Will be set from dropdown selection
        designation_id: null, // Will be set from dropdown selection
      });
    }
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-3xl font-bold text-gray-900">Profile</h1>
        {!isEditing ? (
          <button 
            onClick={() => setIsEditing(true)}
            className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Edit className="h-4 w-4 mr-2" />
            Edit Profile
          </button>
        ) : (
          <div className="flex items-center space-x-2">
            <button 
              onClick={handleCancel}
              className="flex items-center px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors"
            >
              <X className="h-4 w-4 mr-2" />
              Cancel
            </button>
            <button 
              onClick={handleSubmit}
              disabled={loading}
              className="flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50"
            >
              <Save className="h-4 w-4 mr-2" />
              {loading ? 'Saving...' : 'Save Changes'}
            </button>
          </div>
        )}
      </div>

      {/* Message Display */}
      {message && (
        <div className={`p-4 rounded-lg flex items-center ${
          message.type === 'success' 
            ? 'bg-green-50 border border-green-200 text-green-800' 
            : 'bg-red-50 border border-red-200 text-red-800'
        }`}>
          {message.type === 'success' ? (
            <CheckCircle className="h-5 w-5 mr-2" />
          ) : (
            <AlertCircle className="h-5 w-5 mr-2" />
          )}
          <span className="flex-1">{message.text}</span>
          <button
            onClick={() => setMessage(null)}
            className="ml-2 text-gray-400 hover:text-gray-600"
          >
            <X className="h-4 w-4" />
          </button>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Profile Card */}
        <div className="lg:col-span-1">
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <div className="text-center">
              <div className="w-24 h-24 bg-blue-600 rounded-full flex items-center justify-center text-white text-2xl font-bold mx-auto mb-4">
                {user.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
              </div>
              
              <h2 className="text-xl font-semibold text-gray-900">{user.name}</h2>
              {/* <p className="text-gray-600">{user.rank}</p> */}
              {/* <p className="text-sm text-gray-500 mt-1">{user.service_no}</p> */}
              
              {/* <div className="flex justify-center mt-4">
                <div className={`px-3 py-1 rounded-full text-sm font-medium ${
                  user.status === 'online' ? 'bg-green-100 text-green-800' :
                  user.status === 'busy' ? 'bg-yellow-100 text-yellow-800' :
                  'bg-gray-100 text-gray-800'
                }`}>
                  {user.status.charAt(0).toUpperCase() + user.status.slice(1)}
                </div>
              </div> */}
            </div>

            {/* <div className="mt-6 space-y-4">
              <div className="flex items-center space-x-3">
                <Phone className="h-5 w-5 text-gray-400" />
                <span className="text-sm text-gray-900">{user.phone}</span>
              </div>
              <div className="flex items-center space-x-3">
                <Mail className="h-5 w-5 text-gray-400" />
                <span className="text-sm text-gray-900">{user.email}</span>
              </div>
              <div className="flex items-center space-x-3">
                <MapPin className="h-5 w-5 text-gray-400" />
                <span className="text-sm text-gray-900">{user.unit}, {user.branch}</span>
              </div>
              <div className="flex items-center space-x-3">
                <Shield className="h-5 w-5 text-gray-400" />
                <span className="text-sm text-gray-900">{user.role}</span>
              </div>
            </div> */}
          </div>
        </div>

        {/* Details */}
        <div className="lg:col-span-2 space-y-6">
          {/* Personal Information */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Personal Information</h3>
            <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">Full Name</label>
                {isEditing ? (
                  <input
                    type="text"
                    name="name"
                    value={formData.name}
                    onChange={handleInputChange}
                    className="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="Enter full name"
                  />
                ) : (
                  <div className="p-3 bg-gray-50 rounded-lg text-sm">{user.name}</div>
                )}
              </div>
              
              {/* <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Service Number</label>
                {isEditing ? (
                  <input
                    type="text"
                    name="service_no"
                    value={formData.service_no}
                    onChange={handleInputChange}
                    className="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="Enter service number"
                    maxLength={20}
                  />
                ) : (
                  <div className="p-3 bg-gray-50 rounded-lg text-sm">{user.service_no}</div>
                )}
              </div> */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Role</label>
                <div className="p-3 bg-gray-50 rounded-lg text-sm">{user.role}</div>
              </div>
            </div>
          </div>

          {/* Contact Information */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Contact Information</h3>
            <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">Email Address</label>
                {isEditing ? (
                  <input
                    type="email"
                    name="email"
                    value={formData.email}
                    onChange={handleInputChange}
                    className="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="Enter email address"
                  />
                ) : (
                  <div className="p-3 bg-gray-50 rounded-lg text-sm">{user.email}</div>
                )}
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">LOGIN ACCESS</label>
                <div className="p-3 bg-gray-50 rounded-lg text-sm">LOGIN ACCESS</div>
              </div>
            </div>
          </div>

          {/* Assignment Information */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Service Information</h3>
            <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">Unit</label>
                {isEditing ? (
                  <select
                    name="unit_id"
                    value={formData.unit_id || ''}
                    onChange={handleInputChange}
                    className="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    disabled={dataLoading}
                  >
                    <option value="">Select Unit</option>
                    {units.map((unit) => (
                      <option key={unit.id} value={unit.id}>{unit.name}</option>
                    ))}
                  </select>
                ) : (
                  <div className="p-3 bg-gray-50 rounded-lg text-sm">{user.unit}</div>
                )}
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Department</label>
                {isEditing ? (
                  <select
                    name="department_id"
                    value={formData.department_id || ''}
                    onChange={handleInputChange}
                    className="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    disabled={dataLoading}
                  >
                    <option value="">Select Department</option>
                    {departments.map((dept) => (
                      <option key={dept.id} value={dept.id}>{dept.name}</option>
                    ))}
                  </select>
                ) : (
                  <div className="p-3 bg-gray-50 rounded-lg text-sm">{user.department}</div>
                )}
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Designation</label>
                {isEditing ? (
                  <select
                    name="designation_id"
                    value={formData.designation_id || ''}
                    onChange={handleInputChange}
                    className="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    disabled={dataLoading}
                  >
                    <option value="">Select Designation</option>
                    {designations.map((designation) => (
                      <option key={designation.id} value={designation.id}>{designation.name}</option>
                    ))}
                  </select>
                ) : (
                  <div className="p-3 bg-gray-50 rounded-lg text-sm">{user.designation}</div>
                )}
              </div>
              {/* <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Rank</label>
                {isEditing ? (
                  <select
                    name="rank_id"
                    value={formData.rank_id || ''}
                    onChange={handleInputChange}
                    className="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    disabled={dataLoading}
                  >
                    <option value="">Select Rank</option>
                    {ranks.map((rank) => (
                      <option key={rank.id} value={rank.id}>{rank.name}</option>
                    ))}
                  </select>
                ) : (
                  <div className="p-3 bg-gray-50 rounded-lg text-sm">{user.rank}</div>
                )}
              </div> */}
            </div>
          </div>

          {/* Security Settings */}
          {/* <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Security Settings</h3>
            <div className="space-y-4">
              <button className="w-full md:w-auto px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors">
                Change Password
              </button>
              <button className="w-full md:w-auto px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors ml-0 md:ml-3">
                Two-Factor Authentication
              </button>
            </div>
          </div> */}
        </div>
      </div>
    </div>
  );
};

export default Profile;
