import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import axiosInstance from '../../../utils/axiosConfig';
import { listFromSatResponse } from '../../../utils/satApiResponse';
import {
    siteRowId,
    siteRowLabel,
    departmentRowId,
    departmentRowLabel
} from '../../../utils/masterDashboardLocationUtils';
import { AUDITS_URL, COUNTRY_URL, LOCATIONS_URL, USERS_URL, EXTERNAL_AUDITORS_URL } from '../../../utils/config';
import { getUserIdFromToken, getDisplayNameFromToken } from '../../../utils/authUtils';
import { getCachedAuditInfo, setCachedAuditInfo, clearAllCreateAuditCache } from '../../../utils/createAuditObservationsCache';
import ErrorPopup from '../../common/ErrorPopup';
import { useScrollToError } from '../../../hooks/useScrollToError';
import './styles/CreateAudit.css';

const CreateAudit = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const [formData, setFormData] = useState(() => ({
        auditor_id: String(getUserIdFromToken() || ''),
        audit_name: '',
        country: '',
        location: '',
        work_area: '',
        observed_at: '', // manual observation date
        start_time: '',
        end_time: '',
        coauditors: [],
        auditees: []
    }));
    const [users, setUsers] = useState([]);
    const [countries, setCountries] = useState([]);
    const [locations, setLocations] = useState([]);
    const [departments, setDepartments] = useState([]);
    const [loading, setLoading] = useState(false);
    const [fetchingData, setFetchingData] = useState(true);
    const [error, setError] = useState(null);
    const [formSubmitted, setFormSubmitted] = useState(false);
    const [coauditorType, setCoauditorType] = useState(''); // '' | 0 (Internal) | 1 (External)
    const [coauditorSearchQuery, setCoauditorSearchQuery] = useState('');
    const [externalAuditorsList, setExternalAuditorsList] = useState([]);
    const [externalAuditorsLoading, setExternalAuditorsLoading] = useState(false);
    const [showAddExternalModal, setShowAddExternalModal] = useState(false);
    const [newExternalForm, setNewExternalForm] = useState({ full_name: '', email: '', organization: '' });
    const [addingExternal, setAddingExternal] = useState(false);
    const [addExternalError, setAddExternalError] = useState('');
    const [showCoauditorDropdown, setShowCoauditorDropdown] = useState(false);
    const coauditorDropdownRef = useRef(null);
    const [showAuditeeDropdown, setShowAuditeeDropdown] = useState(false);
    const auditeeDropdownRef = useRef(null);
    const [auditeeSearchQuery, setAuditeeSearchQuery] = useState('');
    const [infoSavedToCache, setInfoSavedToCache] = useState(false);

    useScrollToError(error);

    // Body class so global CSS can shrink main content and remove empty space below form
    useEffect(() => {
        document.body.classList.add('create-audit-route');
        return () => document.body.classList.remove('create-audit-route');
    }, []);

    // On mount: restore from cache if user is returning from observations page
    useEffect(() => {
        const cachedInfo = getCachedAuditInfo();
        if (cachedInfo && Object.keys(cachedInfo).length > 0) {
            setFormData(prev => ({ ...prev, ...cachedInfo }));
            setInfoSavedToCache(true);
        }
    }, []);

    // Fetch users and countries on mount (independent: one failure must not blank the other).
    useEffect(() => {
        const fetchData = async () => {
            setFetchingData(true);
            setError(null);
            try {
                const fetchUsersList = async () => {
                    try {
                        const res = await axiosInstance.get(USERS_URL);
                        return { ok: true, list: listFromSatResponse(res) };
                    } catch (err) {
                        if (err.response?.status === 403) return { ok: true, list: [] };
                        console.error('CreateAudit: users list failed:', err.response?.data || err.message);
                        return { ok: false, list: [] };
                    }
                };
                const fetchCountriesList = async () => {
                    try {
                        const res = await axiosInstance.get(COUNTRY_URL);
                        return { ok: true, list: listFromSatResponse(res) };
                    } catch (err) {
                        if (err.response?.status === 403) return { ok: true, list: [] };
                        console.error('CreateAudit: countries failed:', err.response?.data || err.message);
                        return { ok: false, list: [] };
                    }
                };

                const [usersResult, countriesResult] = await Promise.all([
                    fetchUsersList(),
                    fetchCountriesList()
                ]);

                setUsers(usersResult.list);
                setCountries(countriesResult.list);

                if (!countriesResult.ok) {
                    setError('Failed to load countries. Check API / database and refresh.');
                }
                // Users list failure: do not block country/location; co-auditor/auditee dropdowns stay empty until fixed server-side.
            } catch (error) {
                console.error('Error fetching audit page data:', error);
                setError('Failed to load audit data. Please refresh the page.');
            } finally {
                setFetchingData(false);
            }
        };

        fetchData();
    }, []);

    // Auto-fill auditor with the logged-in user (fallback if initial state missed it)
    useEffect(() => {
        const loggedInUserId = getUserIdFromToken();
        if (loggedInUserId == null) return;
        setFormData((prev) => {
            if (!prev.auditor_id) {
                return { ...prev, auditor_id: String(loggedInUserId) };
            }
            return prev;
        });
    }, []);

    // Fetch locations for the selected country (filtered by country)
    useEffect(() => {
        if (!formData.country || formData.country === '') {
            setLocations([]);
            return;
        }
        const countryId = formData.country;
        const fetchLocationsForCountry = async () => {
            try {
                const res = await axiosInstance.get(`${LOCATIONS_URL}/country/${countryId}`);
                setLocations(listFromSatResponse(res));
            } catch (err) {
                if (err.response?.status !== 403) {
                    console.error('Error fetching locations for country:', err);
                    setLocations([]);
                }
            }
        };
        fetchLocationsForCountry();
    }, [formData.country]);

    // Fetch departments for the selected location (filtered by location)
    useEffect(() => {
        if (!formData.location || formData.location === '') {
            setDepartments([]);
            return;
        }
        const locationId = formData.location;
        const fetchDepartmentsForLocation = async () => {
            try {
                const res = await axiosInstance.get(`${LOCATIONS_URL}/${locationId}/departments`);
                setDepartments(listFromSatResponse(res));
            } catch (err) {
                if (err.response?.status !== 403) {
                    console.error('Error fetching departments for location:', err);
                    setDepartments([]);
                }
            }
        };
        fetchDepartmentsForLocation();
    }, [formData.location]);

    // Hot search: fetch external auditors when type is External (debounced)
    useEffect(() => {
        if (coauditorType !== 1) {
            setExternalAuditorsList([]);
            return;
        }
        const timer = setTimeout(async () => {
            setExternalAuditorsLoading(true);
            try {
                const q = coauditorSearchQuery.trim();
                const res = await axiosInstance.get(EXTERNAL_AUDITORS_URL, { params: q ? { q } : {} });
                setExternalAuditorsList(res.data?.data || []);
            } catch (err) {
                if (err.response?.status !== 403) setExternalAuditorsList([]);
            } finally {
                setExternalAuditorsLoading(false);
            }
        }, 300);
        return () => clearTimeout(timer);
    }, [coauditorType, coauditorSearchQuery]);

    // Close coauditor dropdown when clicking outside
    useEffect(() => {
        if (!showCoauditorDropdown) return;
        const handleClick = (e) => {
            if (coauditorDropdownRef.current && !coauditorDropdownRef.current.contains(e.target)) {
                setShowCoauditorDropdown(false);
            }
        };
        document.addEventListener('mousedown', handleClick);
        return () => document.removeEventListener('mousedown', handleClick);
    }, [showCoauditorDropdown]);

    // Close auditee dropdown when clicking outside
    useEffect(() => {
        if (!showAuditeeDropdown) return;
        const handleClick = (e) => {
            if (auditeeDropdownRef.current && !auditeeDropdownRef.current.contains(e.target)) {
                setShowAuditeeDropdown(false);
            }
        };
        document.addEventListener('mousedown', handleClick);
        return () => document.removeEventListener('mousedown', handleClick);
    }, [showAuditeeDropdown]);

    // Prevent closing tab/window while creating audit
    useEffect(() => {
        const handleBeforeUnload = (e) => {
            if (!formSubmitted) {
                e.preventDefault();
                e.returnValue = 'You have unsaved changes. Are you sure you want to leave?';
                return e.returnValue;
            }
        };

        window.addEventListener('beforeunload', handleBeforeUnload);

        return () => {
            window.removeEventListener('beforeunload', handleBeforeUnload);
        };
    }, [formSubmitted]);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setError(null);
        setFormData(prev => {
            const next = { ...prev, [name]: value };
            // When country changes, clear location and work area
            if (name === 'country') {
                next.location = '';
                next.work_area = '';
            }
            // When location changes, clear work area so user must pick a department for the new location
            if (name === 'location') {
                next.work_area = '';
            }
            return next;
        });
    };

    // Keep cache in sync when user edits after clicking Continue
    useEffect(() => {
        if (infoSavedToCache && formData.auditor_id) {
            setCachedAuditInfo(formData);
        }
    }, [infoSavedToCache, formData]);

    const internalOptions = coauditorType === 0 && users.length > 0
        ? users.filter(
            u => {
                const matchesSearch =
                    (u.employee_name || '').toLowerCase().includes((coauditorSearchQuery || '').trim().toLowerCase()) ||
                    (u.email_id || '').toLowerCase().includes((coauditorSearchQuery || '').trim().toLowerCase());
                const alreadyAdded = formData.coauditors.some(
                    c => c.co_auditor_type === 0 && Number(c.co_auditor_user_id) === Number(u.user_id)
                );
                return matchesSearch && !alreadyAdded;
            }
        )
        : [];

    const externalOptionsAvailable = externalAuditorsList.filter(
        ext => !formData.coauditors.some(
            c => c.co_auditor_type === 1 && Number(c.external_auditor_id) === Number(ext.external_auditor_id)
        )
    );

    const openAddExternalModal = () => {
        setShowAddExternalModal(true);
        setNewExternalForm({ full_name: '', email: '', organization: '' });
        setAddExternalError('');
        setShowCoauditorDropdown(false);
    };

    const submitNewExternalAuditor = async (e) => {
        e.preventDefault();
        if (!newExternalForm.full_name.trim()) {
            setError('Full name is required for external auditor.');
            return;
        }
        setAddingExternal(true);
        setError(null);
        setAddExternalError('');
        try {
            const res = await axiosInstance.post(EXTERNAL_AUDITORS_URL, {
                full_name: newExternalForm.full_name.trim(),
                email: newExternalForm.email.trim() || undefined,
                organization: newExternalForm.organization.trim() || undefined
            });
            const created = res.data?.data;
            if (created) {
                setExternalAuditorsList(prev => [...prev, created]);
                setFormData(prev => ({
                    ...prev,
                    coauditors: [...prev.coauditors, {
                        co_auditor_type: 1,
                        external_auditor_id: created.external_auditor_id,
                        co_auditor_name: created.full_name || ''
                    }]
                }));
                setShowAddExternalModal(false);
                setNewExternalForm({ full_name: '', email: '', organization: '' });
            }
        } catch (err) {
            const msg = err.response?.data?.message
                || err.response?.data?.error
                || (err.response?.status ? `Request failed (${err.response.status})` : err.message)
                || 'Failed to add external auditor.';
            setAddExternalError(msg);
            setError(msg);
        } finally {
            setAddingExternal(false);
        }
    };

    const removeCoauditor = (index) => {
        setFormData(prev => ({
            ...prev,
            coauditors: prev.coauditors.filter((_, i) => i !== index)
        }));
    };

    const removeAuditee = (userId) => {
        setFormData(prev => ({
            ...prev,
            auditees: prev.auditees.filter(id => id !== userId)
        }));
    };

    const handleContinueToObservations = () => {
        setError(null);
        if (!formData.auditor_id || formData.auditor_id === '') {
            setError('Auditor is required.');
            return;
        }
        if (!formData.audit_name || formData.audit_name.trim() === '') {
            setError('Audit Name is required.');
            return;
        }
        if (!formData.country || formData.country === '') {
            setError('Country is required.');
            return;
        }
        if (!formData.location || formData.location === '') {
            setError('Location is required.');
            return;
        }
        if (!formData.work_area || formData.work_area === '') {
            setError('Work Area is required.');
            return;
        }
        if (!formData.observed_at || formData.observed_at.trim() === '') {
            setError('Observed Date is required.');
            return;
        }
        const auditorId = Number(formData.auditor_id);
        const countryId = Number(formData.country);
        const locationId = Number(formData.location);
        const workAreaId = Number(formData.work_area);
        if (isNaN(auditorId) || isNaN(countryId) || isNaN(locationId) || isNaN(workAreaId)) {
            setError('Invalid auditor, country, location, or work area. Please refresh and try again.');
            return;
        }
        setCachedAuditInfo(formData);
        setInfoSavedToCache(true);
        navigate('/create-audit-observations');
    };

    if (fetchingData) {
        return (
            <div className="create-audit-container">
                <div style={{ textAlign: 'center', padding: '2rem' }}>
                    <p>Loading audit data...</p>
                </div>
            </div>
        );
    }

    const errorMessage = error || location.state?.message;
    return (
        <>
            <ErrorPopup
                show={!!errorMessage}
                message={errorMessage || ''}
                onClose={() => { setError(null); }}
            />
            <div className="create-audit-container">
            <div className="create-audit-header">
                <h1 className="create-audit-title">Create New Audit</h1>
                <button
                    className="btn btn-secondary"
                    onClick={() => {
                        setFormSubmitted(true);
                        clearAllCreateAuditCache();
                        navigate('/dashboard');
                    }}
                >
                    Cancel
                </button>
            </div>

            {errorMessage && (
                <div className="error-message">
                    {errorMessage}
                </div>
            )}

            <form onSubmit={(e) => e.preventDefault()}>
                <div className="form-grid">
                    <div className="form-group">
                        <label htmlFor="auditor_display" className="form-label">
                            Auditor <span style={{ color: 'red' }}>*</span>
                        </label>
                        <input
                            type="text"
                            id="auditor_display"
                            className="form-input form-input-disabled"
                            value={getDisplayNameFromToken() || '—'}
                            readOnly
                            disabled
                            tabIndex={-1}
                            aria-label="Auditor (logged-in user)"
                        />
                    </div>

                    <div className="form-group">
                        <label htmlFor="audit_name" className="form-label">
                            Audit Name <span style={{ color: 'red' }}>*</span>
                        </label>
                        <input
                            type="text"
                            id="audit_name"
                            name="audit_name"
                            className="form-input"
                            value={formData.audit_name}
                            onChange={handleChange}
                            placeholder="Enter audit name"
                            required
                        />
                    </div>
                </div>

                <div className="form-grid">
                    <div className="form-group">
                        <label htmlFor="country" className="form-label">
                            Country <span style={{ color: 'red' }}>*</span>
                        </label>
                        <select
                            id="country"
                            name="country"
                            className="form-input"
                            value={formData.country}
                            onChange={handleChange}
                            required
                        >
                            <option value="">Select Country</option>
                            {countries.map(c => (
                                <option key={c.country_id} value={c.country_id}>
                                    {c.country_name}
                                </option>
                            ))}
                        </select>
                    </div>

                    <div className="form-group">
                        <label htmlFor="location" className="form-label">
                            Location <span style={{ color: 'red' }}>*</span>
                        </label>
                        <select
                            id="location"
                            name="location"
                            className="form-input"
                            value={formData.location}
                            onChange={handleChange}
                            required
                            disabled={!formData.country}
                        >
                            <option value="">
                                {formData.country ? 'Select Location' : 'Select country first'}
                            </option>
                            {locations.map((location) => {
                                const lid = siteRowId(location);
                                if (lid === '' || lid == null) return null;
                                const locType = location.location_type ?? location.Location_Type ?? location.locationType;
                                const typeSuffix = locType ? ` (${locType})` : '';
                                return (
                                    <option key={String(lid)} value={String(lid)}>
                                        {siteRowLabel(location)}
                                        {typeSuffix}
                                    </option>
                                );
                            })}
                        </select>
                    </div>

                </div>

                <div className="form-grid">
                    <div className="form-group">
                        <label htmlFor="work_area" className="form-label">
                            Work Area <span style={{ color: 'red' }}>*</span>
                        </label>
                        <select
                            id="work_area"
                            name="work_area"
                            className="form-input"
                            value={formData.work_area}
                            onChange={handleChange}
                            required
                            disabled={!formData.location}
                        >
                            <option value="">
                                {formData.location ? 'Select Work Area' : 'Select location first'}
                            </option>
                            {departments.map((dept) => {
                                const did = departmentRowId(dept);
                                if (did === '' || did == null) return null;
                                return (
                                    <option key={String(did)} value={String(did)}>
                                        {departmentRowLabel(dept)}
                                    </option>
                                );
                            })}
                        </select>
                    </div>
                    <div className="form-group">
                        <label htmlFor="observed_at" className="form-label">
                            Observed Date <span style={{ color: 'red' }}>*</span>
                        </label>
                        <input
                            type="date"
                            id="observed_at"
                            name="observed_at"
                            className="form-input"
                            value={formData.observed_at}
                            onChange={handleChange}
                            required
                        />
                    </div>
                </div>

                <div className="form-grid">
                    <div className="form-group">
                        <label htmlFor="start_time" className="form-label">
                            Start Time (Optional)
                        </label>
                        <input
                            type="time"
                            id="start_time"
                            name="start_time"
                            className="form-input"
                            value={formData.start_time}
                            onChange={handleChange}
                            aria-label="Start time optional"
                        />
                    </div>
                    <div className="form-group">
                        <label htmlFor="end_time" className="form-label">
                            End Time (Optional)
                        </label>
                        <input
                            type="time"
                            id="end_time"
                            name="end_time"
                            className="form-input"
                            value={formData.end_time}
                            onChange={handleChange}
                            aria-label="End time optional"
                        />
                    </div>
                </div>

                <div className="form-group">
                    <label className="form-label">
                        Co-Auditors (Optional)
                    </label>
                    <div className="coauditor-input-section">
                        <div className="coauditor-input-group coauditor-dropdown-group">
                            <select
                                className="form-input coauditor-type-select"
                                value={coauditorType}
                                onChange={(e) => {
                                    const v = e.target.value;
                                    setCoauditorType(v === '' ? '' : parseInt(v, 10));
                                    setCoauditorSearchQuery('');
                                    setShowCoauditorDropdown(!!v);
                                }}
                                aria-label="Co-auditor type"
                            >
                                <option value="">Select type (Internal / External)</option>
                                <option value={0}>Internal — from your organization</option>
                                <option value={1}>External — from outside your organization</option>
                            </select>
                            {coauditorType !== '' && (
                                <div className="coauditor-select-row" ref={coauditorDropdownRef}>
                                    <div className="coauditor-search-wrap">
                                        <input
                                            type="text"
                                            className="form-input coauditor-search-input"
                                            placeholder={coauditorType === 0 ? 'Search by name or email...' : 'Search external auditors...'}
                                            value={coauditorSearchQuery}
                                            onChange={(e) => {
                                                setCoauditorSearchQuery(e.target.value);
                                                setShowCoauditorDropdown(true);
                                            }}
                                            onFocus={() => setShowCoauditorDropdown(true)}
                                            aria-label="Search co-auditor"
                                        />
                                        {showCoauditorDropdown && (
                                            <div className="coauditor-dropdown" role="listbox">
                                                {coauditorType === 0 && (
                                                    <>
                                                        {internalOptions.length === 0 ? (
                                                            <div className="coauditor-dropdown-item coauditor-dropdown-empty">
                                                                {users.length === 0
                                                                    ? 'No users loaded'
                                                                    : (() => {
                                                                        const q = (coauditorSearchQuery || '').trim().toLowerCase();
                                                                        const matching = users.filter(u =>
                                                                            (u.employee_name || '').toLowerCase().includes(q) ||
                                                                            (u.email_id || '').toLowerCase().includes(q)
                                                                        );
                                                                        return matching.length > 0 ? 'All matching users already added' : 'No matching users';
                                                                      })()}
                                                            </div>
                                                        ) : (
                                                            internalOptions.map((user) => (
                                                                <div
                                                                    key={user.user_id}
                                                                    className="coauditor-dropdown-item"
                                                                    role="option"
                                                                    onClick={() => {
                                                                        if (formData.coauditors.some(c => c.co_auditor_type === 0 && Number(c.co_auditor_user_id) === Number(user.user_id))) return;
                                                                        setFormData(prev => ({
                                                                            ...prev,
                                                                            coauditors: [...prev.coauditors, {
                                                                                co_auditor_type: 0,
                                                                                co_auditor_user_id: user.user_id,
                                                                                co_auditor_name: user.employee_name || user.email_id || ''
                                                                            }]
                                                                        }));
                                                                        setCoauditorSearchQuery('');
                                                                        setShowCoauditorDropdown(false);
                                                                    }}
                                                                >
                                                                    {user.employee_name} ({user.email_id})
                                                                </div>
                                                            ))
                                                        )}
                                                    </>
                                                )}
                                                {coauditorType === 1 && (
                                                    <>
                                                        {externalAuditorsLoading ? (
                                                            <div className="coauditor-dropdown-item coauditor-dropdown-empty">Loading...</div>
                                                        ) : externalOptionsAvailable.length === 0 && !coauditorSearchQuery.trim() ? (
                                                            <div className="coauditor-dropdown-item coauditor-dropdown-empty">Type to search or add new</div>
                                                        ) : externalOptionsAvailable.length === 0 ? (
                                                            <div className="coauditor-dropdown-item coauditor-dropdown-empty">All matching auditors already added</div>
                                                        ) : (
                                                            externalOptionsAvailable.map((ext) => (
                                                                <div
                                                                    key={ext.external_auditor_id}
                                                                    className="coauditor-dropdown-item"
                                                                    role="option"
                                                                    onClick={() => {
                                                                        if (formData.coauditors.some(c => c.co_auditor_type === 1 && Number(c.external_auditor_id) === Number(ext.external_auditor_id))) return;
                                                                        setFormData(prev => ({
                                                                            ...prev,
                                                                            coauditors: [...prev.coauditors, {
                                                                                co_auditor_type: 1,
                                                                                external_auditor_id: ext.external_auditor_id,
                                                                                co_auditor_name: ext.full_name || ''
                                                                            }]
                                                                        }));
                                                                        setCoauditorSearchQuery('');
                                                                        setShowCoauditorDropdown(false);
                                                                    }}
                                                                >
                                                                    {ext.full_name}
                                                                    {ext.organization ? ` — ${ext.organization}` : ''}
                                                                </div>
                                                            ))
                                                        )}
                                                        <button
                                                            type="button"
                                                            className="coauditor-add-new-btn"
                                                            onClick={openAddExternalModal}
                                                        >
                                                            + Add new external auditor
                                                        </button>
                                                    </>
                                                )}
                                            </div>
                                        )}
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                    {formData.coauditors.length > 0 && (
                        <div className="coauditor-list">
                            {formData.coauditors.map((coauditor, index) => (
                                <div key={index} className="coauditor-item">
                                    <span className="coauditor-name">{coauditor.co_auditor_name}</span>
                                    <span className="coauditor-type-badge">{coauditor.co_auditor_type === 1 ? 'External' : 'Internal'}</span>
                                    <button
                                        type="button"
                                        className="btn-remove"
                                        onClick={() => removeCoauditor(index)}
                                    >
                                        ×
                                    </button>
                                </div>
                            ))}
                        </div>
                    )}
                </div>

                <div className="form-group">
                    <label className="form-label">
                        Auditees (Optional)
                    </label>
                    <div className="auditee-dropdown-group" ref={auditeeDropdownRef}>
                        <button
                            type="button"
                            className={`form-input auditee-trigger ${showAuditeeDropdown ? 'open' : ''}`}
                            onClick={() => setShowAuditeeDropdown(!showAuditeeDropdown)}
                            aria-expanded={showAuditeeDropdown}
                            aria-haspopup="listbox"
                            aria-label="Select auditees"
                        >
                            <span className="auditee-trigger-text">
                                {formData.auditees.length > 0
                                    ? `${formData.auditees.length} auditee(s) selected`
                                    : 'Click to select auditees'}
                            </span>
                            <span className="auditee-trigger-arrow" aria-hidden>▼</span>
                        </button>
                        {showAuditeeDropdown && (
                            <div className="auditee-dropdown-panel" role="listbox">
                                <input
                                    type="text"
                                    className="form-input auditee-search-input-inline"
                                    placeholder="Search by name or email..."
                                    value={auditeeSearchQuery}
                                    onChange={(e) => setAuditeeSearchQuery(e.target.value)}
                                    onClick={(e) => e.stopPropagation()}
                                    aria-label="Search auditees"
                                />
                                <div className="auditee-dropdown-list">
                                    {(() => {
                                        const q = (auditeeSearchQuery || '').trim().toLowerCase();
                                        const filteredUsers = !q
                                            ? users
                                            : users.filter(
                                                (user) =>
                                                    (user.employee_name || '').toLowerCase().includes(q) ||
                                                    (user.email_id || '').toLowerCase().includes(q)
                                            );
                                        if (users.length === 0) {
                                            return (
                                                <div className="auditee-dropdown-empty">No users available</div>
                                            );
                                        }
                                        if (filteredUsers.length === 0) {
                                            return (
                                                <div className="auditee-dropdown-empty">
                                                    No auditees match &quot;{auditeeSearchQuery}&quot;
                                                </div>
                                            );
                                        }
                                        return filteredUsers.map(user => {
                                            const isSelected = formData.auditees.includes(user.user_id);
                                            return (
                                                <div
                                                    key={user.user_id}
                                                    className={`auditee-dropdown-item ${isSelected ? 'selected' : ''}`}
                                                    role="option"
                                                    aria-selected={isSelected}
                                                    onClick={() => {
                                                        setFormData(prev => ({
                                                            ...prev,
                                                            auditees: prev.auditees.includes(user.user_id)
                                                                ? prev.auditees.filter(id => id !== user.user_id)
                                                                : [...prev.auditees, user.user_id]
                                                        }));
                                                    }}
                                                >
                                                    {user.employee_name} ({user.email_id})
                                                </div>
                                            );
                                        });
                                    })()}
                                </div>
                            </div>
                        )}
                    </div>
                    {formData.auditees.length > 0 && (
                        <div className="coauditor-list auditee-list">
                            {formData.auditees.map((userId) => {
                                const user = users.find(u => u.user_id === userId);
                                const displayName = user ? (user.employee_name || user.email_id || `User ${userId}`) : `User ${userId}`;
                                return (
                                    <div key={userId} className="coauditor-item auditee-item">
                                        <span className="coauditor-name">{displayName}</span>
                                        <button
                                            type="button"
                                            className="btn-remove"
                                            onClick={() => removeAuditee(userId)}
                                            aria-label={`Remove ${displayName}`}
                                        >
                                            ×
                                        </button>
                                    </div>
                                );
                            })}
                        </div>
                    )}
                </div>

                <div className="form-actions">
                    <button
                        type="button"
                        className="btn btn-primary"
                        onClick={handleContinueToObservations}
                    >
                        Add Observations
                    </button>
                    <button
                        type="button"
                        className="btn btn-secondary"
                        onClick={() => {
                            const loggedInUserId = getUserIdFromToken();
                            setFormData({
                                auditor_id: loggedInUserId != null ? String(loggedInUserId) : '',
                                audit_name: '',
                                country: '',
                                location: '',
                                work_area: '',
                                observed_at: '',
                                start_time: '',
                                end_time: '',
                                coauditors: [],
                                auditees: []
                            });
                            setAuditeeSearchQuery('');
                            setShowAuditeeDropdown(false);
                            setFormSubmitted(false);
                            clearAllCreateAuditCache();
                            setInfoSavedToCache(false);
                        }}
                    >
                        Reset
                    </button>
                </div>
            </form>

            {/* Add External Auditor modal - outside main form to avoid nested form (which causes page refresh) */}
            {showAddExternalModal && (
                <div className="modal-overlay" onClick={() => !addingExternal && setShowAddExternalModal(false)} role="dialog" aria-modal="true" aria-labelledby="add-external-title">
                    <div className="modal-content coauditor-modal" onClick={(e) => e.stopPropagation()}>
                        <h2 id="add-external-title" className="modal-title">Add External Auditor</h2>
                        {addExternalError && (
                            <div className="error-message" style={{ marginBottom: '1rem' }}>{addExternalError}</div>
                        )}
                        <form onSubmit={submitNewExternalAuditor}>
                            <div className="form-group">
                                <label htmlFor="ext_full_name" className="form-label">Full Name <span style={{ color: 'red' }}>*</span></label>
                                <input
                                    id="ext_full_name"
                                    type="text"
                                    className="form-input"
                                    value={newExternalForm.full_name}
                                    onChange={(e) => setNewExternalForm(prev => ({ ...prev, full_name: e.target.value }))}
                                    placeholder="Enter full name"
                                    required
                                />
                            </div>
                            <div className="form-group">
                                <label htmlFor="ext_email" className="form-label">Email (Optional)</label>
                                <input
                                    id="ext_email"
                                    type="email"
                                    className="form-input"
                                    value={newExternalForm.email}
                                    onChange={(e) => setNewExternalForm(prev => ({ ...prev, email: e.target.value }))}
                                    placeholder="Email"
                                />
                            </div>
                            <div className="form-group">
                                <label htmlFor="ext_organization" className="form-label">Organization (Optional)</label>
                                <input
                                    id="ext_organization"
                                    type="text"
                                    className="form-input"
                                    value={newExternalForm.organization}
                                    onChange={(e) => setNewExternalForm(prev => ({ ...prev, organization: e.target.value }))}
                                    placeholder="Organization"
                                />
                            </div>
                            <div className="modal-actions">
                                <button type="button" className="btn btn-secondary" onClick={() => !addingExternal && setShowAddExternalModal(false)} disabled={addingExternal}>Cancel</button>
                                <button type="submit" className="btn btn-primary" disabled={addingExternal}>{addingExternal ? 'Adding...' : 'Add & Select'}</button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
        </>
    );
};

export default CreateAudit;
