import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useMaintenanceTeamDetails, useMaintenanceTeamMutations } from '../hooks/useMaintenanceTeam';
import { 
  FaArrowLeft, 
  FaSave, 
  FaEdit, 
  FaTrash,
  FaCheckCircle,
  FaTimesCircle,
  FaExclamationTriangle,
  FaUsers,
  FaUserTie,
  FaBuilding,
  FaPlus,
  FaUserPlus,
  FaTimes
} from 'react-icons/fa';
import { toast, ToastContainer, Bounce } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import LinkField from '../components/LinkField';
import type { CreateMaintenanceTeamData, MaintenanceTeamMember } from '../services/maintenanceTeamService';

const MaintenanceTeamDetail: React.FC = () => {
  const { t } = useTranslation();
  const { teamName } = useParams<{ teamName: string }>();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  
  const isNewTeam = teamName === 'new';
  const duplicateFrom = searchParams.get('duplicate');

  const [formData, setFormData] = useState<CreateMaintenanceTeamData>({
    maintenance_team_name: '',
    maintenance_manager: '',
    maintenance_manager_name: '',
    company: '',
    custom_expertise: '',
    maintenance_team_members: [],
  });

  const { team, loading, error, refetch } = useMaintenanceTeamDetails(
    isNewTeam ? (duplicateFrom || null) : (teamName || null)
  );
  const { createTeam, updateTeam, deleteTeam, getUserFullName, loading: saving } = useMaintenanceTeamMutations();

  const [isEditing, setIsEditing] = useState(isNewTeam);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [showDeleteMemberConfirm, setShowDeleteMemberConfirm] = useState<number | null>(null);
  const [checkingMember, setCheckingMember] = useState<number | null>(null); // Track which row is being checked

  // Check if a team member exists in other teams
  const checkMemberInOtherTeams = async (memberEmail: string): Promise<{ exists: boolean; teamName?: string }> => {
    if (!memberEmail) return { exists: false };
    
    try {
      // Method 1: Try querying via run_doc_method or SQL
      const response = await fetch('/api/method/frappe.client.get_list', {
        method: 'POST',
        headers: { 
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({
          doctype: 'Asset Maintenance Team',
          filters: {},
          fields: ['name', 'maintenance_team_name', 'maintenance_team_members.team_member'],
          limit_page_length: 0, // Get all
        })
      });

      if (!response.ok) {
        // Fallback: Query all teams and check manually
        return await checkMemberInOtherTeamsFallback(memberEmail);
      }

      const data = await response.json();
      const results = data.message || [];
      
      // Check each team for the member
      for (const teamData of results) {
        // Skip current team
        if (teamData.name === teamName || teamData.name === team?.name) continue;
        
        if (teamData['maintenance_team_members.team_member'] === memberEmail) {
          return { exists: true, teamName: teamData.maintenance_team_name || teamData.name };
        }
      }
      
      // If the above doesn't work, use fallback
      return await checkMemberInOtherTeamsFallback(memberEmail);
    } catch (error) {
      console.error('Error checking member in other teams:', error);
      // Try fallback method
      return await checkMemberInOtherTeamsFallback(memberEmail);
    }
  };

  // Fallback method: Fetch all teams with their members
  const checkMemberInOtherTeamsFallback = async (memberEmail: string): Promise<{ exists: boolean; teamName?: string }> => {
    try {
      // Get list of all maintenance teams
      const listResponse = await fetch('/api/resource/Asset Maintenance Team?fields=["name","maintenance_team_name"]&limit_page_length=0', {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
      });

      if (!listResponse.ok) return { exists: false };

      const listData = await listResponse.json();
      const teams = listData.data || [];

      // Check each team's members
      for (const teamInfo of teams) {
        // Skip current team
        if (teamInfo.name === teamName || teamInfo.name === team?.name) continue;

        // Fetch full team details including members
        const teamResponse = await fetch(`/api/resource/Asset Maintenance Team/${encodeURIComponent(teamInfo.name)}`, {
          method: 'GET',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
        });

        if (!teamResponse.ok) continue;

        const teamData = await teamResponse.json();
        const members = teamData.data?.maintenance_team_members || [];

        // Check if member exists in this team
        const memberExists = members.some((m: any) => m.team_member === memberEmail);
        
        if (memberExists) {
          return { 
            exists: true, 
            teamName: teamData.data?.maintenance_team_name || teamInfo.name 
          };
        }
      }

      return { exists: false };
    } catch (error) {
      console.error('Fallback check failed:', error);
      return { exists: false };
    }
  };

  // Load team data when fetched
  useEffect(() => {
    if (team) {
      setFormData({
        maintenance_team_name: isNewTeam && duplicateFrom ? `${team.maintenance_team_name} (Copy)` : team.maintenance_team_name || '',
        maintenance_manager: team.maintenance_manager || '',
        maintenance_manager_name: team.maintenance_manager_name || '',
        company: team.company || '',
        custom_expertise: team.custom_expertise || '',
        maintenance_team_members: team.maintenance_team_members?.map((m, idx) => ({
          ...m,
          idx: idx + 1,
          name: isNewTeam ? undefined : m.name, // Clear name for duplicates
        })) || [],
      });
      if (!isNewTeam) setIsEditing(false);
    }
  }, [team, isNewTeam, duplicateFrom]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  // Handle manager change and fetch full name
  const handleManagerChange = async (email: string) => {
    setFormData(prev => ({ ...prev, maintenance_manager: email }));
    if (email) {
      const fullName = await getUserFullName(email);
      setFormData(prev => ({ ...prev, maintenance_manager_name: fullName }));
    } else {
      setFormData(prev => ({ ...prev, maintenance_manager_name: '' }));
    }
  };

  // Handle team member change
  const handleMemberChange = async (index: number, field: string, value: string) => {
    // If team_member changed, fetch full name and check for duplicates
    if (field === 'team_member' && value) {
      // Check if member is already in current team (other rows)
      const existsInCurrentTeam = formData.maintenance_team_members?.some(
        (m, i) => i !== index && m.team_member === value
      );
      
      if (existsInCurrentTeam) {
        toast.error('This member is already added to this team!', {
          position: "top-right",
          autoClose: 4000,
          icon: <FaTimesCircle />,
        });
        return; // Don't update if already in current team
      }

      // Show checking state
      setCheckingMember(index);
      toast.info('Checking member availability...', {
        position: "top-right",
        autoClose: 2000,
        icon: () => <span>🔍</span>,
      });

      // Check if member exists in other teams
      const { exists, teamName: otherTeamName } = await checkMemberInOtherTeams(value);
      setCheckingMember(null);

      if (exists) {
        toast.error(
          <div>
            <strong>Cannot add member!</strong>
            <br />
            <span className="text-sm">This member is already assigned to: <b>{otherTeamName}</b></span>
          </div>,
          {
            position: "top-right",
            autoClose: 5000,
            icon: <FaTimesCircle />,
          }
        );
        return; // Don't update if already in another team
      }

      // Fetch full name
      const fullName = await getUserFullName(value);
      
      // Update the member data
      const updatedMembers = [...(formData.maintenance_team_members || [])];
      updatedMembers[index] = { 
        ...updatedMembers[index], 
        team_member: value,
        full_name: fullName 
      };
      setFormData(prev => ({ ...prev, maintenance_team_members: updatedMembers }));
      
      toast.success('Member added successfully!', {
        position: "top-right",
        autoClose: 2000,
        icon: <FaCheckCircle />,
      });
    } else {
      // For other fields (like role), just update directly
      const updatedMembers = [...(formData.maintenance_team_members || [])];
      updatedMembers[index] = { ...updatedMembers[index], [field]: value };
      setFormData(prev => ({ ...prev, maintenance_team_members: updatedMembers }));
    }
  };

  // Add new team member
  const handleAddMember = () => {
    const newMember: MaintenanceTeamMember = {
      team_member: '',
      full_name: '',
      maintenance_role: '',
      idx: (formData.maintenance_team_members?.length || 0) + 1,
    };
    setFormData(prev => ({
      ...prev,
      maintenance_team_members: [...(prev.maintenance_team_members || []), newMember],
    }));
  };

  // Remove team member
  const handleRemoveMember = (index: number) => {
    const updatedMembers = formData.maintenance_team_members?.filter((_, i) => i !== index) || [];
    // Re-index
    updatedMembers.forEach((m, i) => { m.idx = i + 1; });
    setFormData(prev => ({ ...prev, maintenance_team_members: updatedMembers }));
    setShowDeleteMemberConfirm(null);
  };

  const handleSave = async () => {
    if (!formData.maintenance_team_name) {
      toast.error('Please enter a team name', { position: "top-right", autoClose: 4000, icon: <FaTimesCircle /> });
      return;
    }

    try {
      // Clean up member data for submission
      const cleanedData = {
        ...formData,
        maintenance_team_members: formData.maintenance_team_members?.map(m => ({
          team_member: m.team_member,
          full_name: m.full_name,
          maintenance_role: m.maintenance_role,
        })).filter(m => m.team_member), // Only include members with team_member set
      };

      if (isNewTeam) {
        const newTeam = await createTeam(cleanedData);
        toast.success('Maintenance Team created successfully!', { position: "top-right", autoClose: 3000, icon: <FaCheckCircle /> });
        navigate(`/maintenance-teams/${newTeam.name}`);
      } else {
        await updateTeam(teamName!, cleanedData);
        toast.success('Maintenance Team updated successfully!', { position: "top-right", autoClose: 3000, icon: <FaCheckCircle /> });
        setIsEditing(false);
        refetch();
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      toast.error(`Failed to save: ${errorMessage}`, { position: "top-right", autoClose: 6000, icon: <FaTimesCircle /> });
    }
  };

  const handleDelete = async () => {
    try {
      await deleteTeam(teamName!);
      toast.success('Maintenance Team deleted successfully!', { position: "top-right", autoClose: 3000, icon: <FaCheckCircle /> });
      navigate('/maintenance-teams');
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      toast.error(`Failed to delete: ${errorMessage}`, { position: "top-right", autoClose: 6000, icon: <FaTimesCircle /> });
    }
  };

  const isFieldDisabled = useCallback((fieldname: string): boolean => {
    if (!isEditing) return true;
    return false;
  }, [isEditing]);

  const formatDateTime = (dateStr?: string) => dateStr ? new Date(dateStr).toLocaleString() : '-';

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-500 mx-auto"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">Loading maintenance team...</p>
        </div>
      </div>
    );
  }

  if (error && !isNewTeam) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-6">
          <h2 className="text-xl font-bold text-red-800 dark:text-red-300 mb-4">{t('maintenance.errorLoadingTeam')}</h2>
          <p className="text-red-700 dark:text-red-400 mb-4">{error}</p>
          <button onClick={() => navigate('/maintenance-teams')} className="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded">{t('maintenance.backToTeams')}</button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 p-6">
      <ToastContainer position="top-right" autoClose={4000} hideProgressBar={false} newestOnTop closeOnClick rtl={false} pauseOnFocusLoss draggable pauseOnHover theme="colored" transition={Bounce} />

      {/* Header */}
      <div className="mb-6 flex justify-between items-center">
        <div className="flex items-center gap-4">
          <button onClick={() => navigate('/maintenance-teams')} className="text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200">
            <FaArrowLeft size={20} />
          </button>
          <div>
            <h1 className="text-2xl font-bold text-gray-800 dark:text-white flex items-center gap-3">
              <FaUsers className="text-indigo-500" />
              {isNewTeam ? 'New Maintenance Team' : team?.maintenance_team_name || 'Maintenance Team'}
            </h1>
            <p className="text-gray-600 dark:text-gray-400 mt-1">
              {isNewTeam ? 'Create a new maintenance team' : team?.name}
            </p>
          </div>
        </div>

        <div className="flex gap-3">
          {!isNewTeam && !isEditing && (
            <>
              <button onClick={() => setIsEditing(true)} className="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-lg flex items-center gap-2">
                <FaEdit />{t('common.edit')}
              </button>
              <button onClick={() => setShowDeleteConfirm(true)} className="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg flex items-center gap-2">
                <FaTrash />{t('common.delete')}
              </button>
            </>
          )}
          {isEditing && (
            <>
              <button onClick={() => { if (isNewTeam) navigate('/maintenance-teams'); else { setIsEditing(false); refetch(); } }} className="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg">
                {t('common.cancel')}
              </button>
              <button onClick={handleSave} disabled={saving} className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 disabled:opacity-50">
                <FaSave />{saving ? t('common.saving') : t('common.save')}
              </button>
            </>
          )}
        </div>
      </div>

      {/* Delete Confirmation Modal */}
      {showDeleteConfirm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-md w-full mx-4 shadow-xl">
            <div className="flex items-start gap-3 mb-4">
              <FaExclamationTriangle className="text-red-500 text-xl mt-0.5" />
              <div>
                <h3 className="text-lg font-semibold text-gray-800 dark:text-white">{t('maintenance.deleteTeam')}</h3>
                <p className="text-gray-600 dark:text-gray-400 mt-1">{t('confirmations.cannotUndo')}</p>
              </div>
            </div>
            <div className="flex justify-end gap-3">
              <button onClick={() => setShowDeleteConfirm(false)} className="px-4 py-2 bg-gray-300 hover:bg-gray-400 text-gray-700 rounded-lg">{t('common.cancel')}</button>
              <button onClick={handleDelete} disabled={saving} className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg disabled:opacity-50">{saving ? t('common.deleting') : t('common.delete')}</button>
            </div>
          </div>
        </div>
      )}

      {/* Form */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Content */}
        <div className="lg:col-span-2 space-y-6">
          {/* Team Information */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaUsers className="text-indigo-500" />{t('maintenance.teamInformation')}
            </h2>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  {t('maintenance.teamName')} <span className="text-red-500">*</span>
                </label>
                <input type="text" name="maintenance_team_name" value={formData.maintenance_team_name} onChange={handleChange} disabled={isFieldDisabled('maintenance_team_name')} placeholder={t('maintenance.enterTeamName')} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500" />
              </div>

              <div>
                <LinkField label={t('commonFields.hospital')} doctype="Company" value={formData.company || ''} onChange={(val) => setFormData({ ...formData, company: val })} disabled={isFieldDisabled('company')} placeholder={t('maintenance.selectHospital')} />
              </div>

              <div>
                <LinkField label={t('maintenance.expertise')} doctype="Issue Type" value={formData.custom_expertise || ''} onChange={(val) => setFormData({ ...formData, custom_expertise: val })} disabled={isFieldDisabled('custom_expertise')} placeholder={t('maintenance.selectExpertise')} />
              </div>

              <div>
                <LinkField label={t('maintenance.manager')} doctype="User" value={formData.maintenance_manager || ''} onChange={handleManagerChange} disabled={isFieldDisabled('maintenance_manager')} placeholder={t('maintenance.selectManager')} />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t('maintenance.managerName')}</label>
                <input type="text" value={formData.maintenance_manager_name || ''} disabled className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400" />
              </div>
            </div>
          </div>

          {/* Team Members */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <div className="flex items-center justify-between mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white flex items-center gap-2">
                <FaUserPlus className="text-green-500" />Team Members
              </h2>
              {isEditing && (
                <button onClick={handleAddMember} disabled={checkingMember !== null} className="bg-green-600 hover:bg-green-700 text-white px-3 py-1.5 rounded-lg flex items-center gap-2 text-sm disabled:opacity-50 disabled:cursor-not-allowed">
                  <FaPlus size={12} />Add Member
                </button>
              )}
            </div>

            {formData.maintenance_team_members && formData.maintenance_team_members.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50 dark:bg-gray-700">
                    <tr>
                      <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">#</th>
                      <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Team Member<span className="text-red-500">*</span></th>
                      <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Full Name</th>
                      <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Role<span className="text-red-500">*</span></th>
                      {isEditing && <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Action</th>}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                    {formData.maintenance_team_members.map((member, index) => (
                      <tr key={index} className={`hover:bg-gray-50 dark:hover:bg-gray-700/50 ${checkingMember === index ? 'opacity-70' : ''}`}>
                        <td className="px-3 py-2 text-sm text-gray-600 dark:text-gray-400">{index + 1}</td>
                        <td className="px-3 py-2">
                          {isEditing ? (
                            <div className="relative">
                              <LinkField label="" doctype="User" value={member.team_member || ''} onChange={(val) => handleMemberChange(index, 'team_member', val)} disabled={checkingMember !== null} placeholder={t('maintenance.selectUser')} compact={true} />
                              {checkingMember === index && (
                                <div className="absolute right-2 top-1/2 -translate-y-1/2">
                                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-indigo-500"></div>
                                </div>
                              )}
                            </div>
                          ) : (
                            <span className="text-sm text-gray-900 dark:text-white">{member.team_member || '-'}</span>
                          )}
                        </td>
                        <td className="px-3 py-2 text-sm text-gray-600 dark:text-gray-300">{member.full_name || '-'}</td>
                        <td className="px-3 py-2">
                          {isEditing ? (
                            <LinkField label="" doctype="Role" value={member.maintenance_role || ''} onChange={(val) => handleMemberChange(index, 'maintenance_role', val)} disabled={checkingMember !== null} placeholder={t('maintenance.selectRole')} compact={true} />
                          ) : (
                            <span className="text-sm text-gray-600 dark:text-gray-300">{member.maintenance_role || '-'}</span>
                          )}
                        </td>
                        {isEditing && (
                          <td className="px-3 py-2 text-center">
                              <button onClick={() => setShowDeleteMemberConfirm(index)} className="text-red-600 dark:text-red-400 hover:text-red-800 dark:hover:text-red-300 p-1.5 hover:bg-red-50 dark:hover:bg-red-900/30 rounded transition-colors" title={t('maintenance.removeMember')}>
                              <FaTrash size={14} />
                            </button>
                          </td>
                        )}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                <FaUsers className="text-4xl mx-auto mb-2 text-gray-300 dark:text-gray-600" />
                <p>{t('maintenance.noTeamMembersYet')}</p>
                {isEditing && (
                  <button onClick={handleAddMember} className="mt-3 text-indigo-600 dark:text-indigo-400 hover:underline">
                    + {t('maintenance.addFirstMember')}
                  </button>
                )}
              </div>
            )}
          </div>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Team Summary Card */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaUserTie className="text-blue-500" />{t('maintenance.teamSummary')}
            </h2>
            
            <div className="space-y-4">
              <div className="p-4 bg-indigo-50 dark:bg-indigo-900/30 rounded-lg border border-indigo-200 dark:border-indigo-800">
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">{t('maintenance.totalMembers')}</p>
                <p className="text-2xl font-bold text-indigo-600 dark:text-indigo-300">
                  {formData.maintenance_team_members?.filter(m => m.team_member).length || 0}
                </p>
              </div>

              {formData.maintenance_manager_name && (
                <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                  <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">{t('maintenance.manager')}</p>
                  <p className="text-sm font-medium text-gray-900 dark:text-white">{formData.maintenance_manager_name}</p>
                </div>
              )}

              {formData.company && (
                <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                  <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">Hospital</p>
                  <p className="text-sm font-medium text-gray-900 dark:text-white">{formData.company}</p>
                </div>
              )}

              {formData.custom_expertise && (
                <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                  <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">Expertise</p>
                  <span className="inline-flex px-2 py-1 text-xs font-medium rounded-full bg-indigo-100 text-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-300">
                    {formData.custom_expertise}
                  </span>
                </div>
              )}
            </div>
          </div>

          {/* Timeline Card */}
          {!isNewTeam && team && (
            <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
                <FaBuilding className="text-teal-500" />Details
              </h2>
              
              <div className="space-y-4">
                <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                  <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">Created</p>
                  <p className="text-sm text-gray-900 dark:text-white">{formatDateTime(team.creation)}</p>
                </div>

                <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                  <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">Last Modified</p>
                  <p className="text-sm text-gray-900 dark:text-white">{formatDateTime(team.modified)}</p>
                </div>

                <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                  <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">Modified By</p>
                  <p className="text-sm text-gray-900 dark:text-white">{team.modified_by || '-'}</p>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Delete Member Confirmation Modal */}
      {showDeleteMemberConfirm !== null && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-sm w-full mx-4 shadow-xl">
            <div className="flex items-start gap-3 mb-4">
              <FaExclamationTriangle className="text-orange-500 text-xl mt-0.5" />
              <div>
                <h3 className="text-lg font-semibold text-gray-800 dark:text-white">Remove Team Member</h3>
                <p className="text-gray-600 dark:text-gray-400 mt-1">Are you sure you want to remove this team member?</p>
              </div>
            </div>
            <div className="flex justify-end gap-3">
              <button onClick={() => setShowDeleteMemberConfirm(null)} className="px-4 py-2 bg-gray-300 hover:bg-gray-400 text-gray-700 rounded-lg">Cancel</button>
              <button onClick={() => handleRemoveMember(showDeleteMemberConfirm)} className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg">Remove</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default MaintenanceTeamDetail;