import React, {useEffect, useState} from 'react';
import Modal from '@/components/ui/modal/Modal';
import {makeGetRequest, makePutRequest} from '@/lib/request';
import {notify} from '@/lib/notify';

const DEFAULT_WORK_SCHEDULE: Record<string, boolean> = {
    monday: true, tuesday: true, wednesday: true, thursday: true, friday: true, saturday: false, sunday: false,
};

const emptyForm = {
    job_title: '', department_id: '', employment_type: 'full_time', employment_status: 'active', salary: '', hourly_rate: '',
    billable_rate: '', overtime_rate: '', bar_admission: '', certifications: '', licenses: '', education: '', practice_areas: '',
    legal_experience_years: '', professional_registration: '', assignment_available: true, workload_capacity: '10',
    work_schedule: {...DEFAULT_WORK_SCHEDULE}, availability_notes: '', supervisor_id: '', start_date: '', contract_end_date: '',
};

const listValue = (value?: unknown): string => Array.isArray(value) ? value.map(item => typeof item === 'object' ? Object.values(item as Record<string, unknown>).filter(Boolean).join(' · ') : String(item)).join(', ') : '';
const splitList = (value: string): string[] => value.split(',').map(item => item.trim()).filter(Boolean);
const records = (response: any): any[] => {
    const payload = response?.data?.result ?? response?.data ?? [];
    return Array.isArray(payload?.data ?? payload) ? (payload.data ?? payload) : [];
};

export default function StaffProfileEditModal({open, profile, token, onClose, onSaved}: {open: boolean; profile: any; token?: string; onClose: () => void; onSaved: (profile: any) => void}): JSX.Element {
    const [form, setForm] = useState({...emptyForm});
    const [departments, setDepartments] = useState<any[]>([]);
    const [staff, setStaff] = useState<any[]>([]);
    const [saving, setSaving] = useState(false);

    useEffect(() => {
        if (!open || !profile) return;
        setForm({
            job_title: profile.job_title || '',
            department_id: profile.department_id ? String(profile.department_id) : '',
            employment_type: profile.employment_type || 'full_time',
            employment_status: profile.employment_status || 'active',
            salary: String(profile.salary || ''), hourly_rate: String(profile.hourly_rate || ''), billable_rate: String(profile.billable_rate || ''), overtime_rate: String(profile.overtime_rate || ''),
            bar_admission: profile.bar_admission || '', certifications: listValue(profile.certifications), licenses: listValue(profile.licenses), education: listValue(profile.education),
            practice_areas: listValue(profile.practice_areas), legal_experience_years: profile.legal_experience_years == null ? '' : String(profile.legal_experience_years),
            professional_registration: listValue(profile.professional_registration), assignment_available: profile.assignment_available !== false,
            workload_capacity: String(profile.workload_capacity || '10'), work_schedule: profile.work_schedule || {...DEFAULT_WORK_SCHEDULE},
            availability_notes: profile.availability_notes || '', supervisor_id: profile.supervisor_id ? String(profile.supervisor_id) : '',
            start_date: profile.start_date ? String(profile.start_date).slice(0, 10) : '', contract_end_date: profile.contract_end_date ? String(profile.contract_end_date).slice(0, 10) : '',
        });
        Promise.all([
            makeGetRequest('/api/hr/departments', {token}),
            makeGetRequest('/api/hr/staff?per_page=200', {token}),
        ]).then(([departmentResponse, staffResponse]) => {
            setDepartments(records(departmentResponse));
            setStaff(records(staffResponse));
        }).catch(error => notify.toastErrorMessage(error?.response?.data?.message || 'Unable to load staff profile options'));
    }, [open, profile, token]);

    async function submit(event: React.FormEvent) {
        event.preventDefault();
        setSaving(true);
        try {
            const response = await makePutRequest(`/api/hr/staff/${profile.id}`, {
                ...form,
                department_id: form.department_id ? Number(form.department_id) : null,
                salary: form.salary || null, hourly_rate: form.hourly_rate || null, billable_rate: form.billable_rate || null, overtime_rate: form.overtime_rate || null,
                certifications: splitList(form.certifications), licenses: splitList(form.licenses), education: splitList(form.education), practice_areas: splitList(form.practice_areas),
                professional_registration: splitList(form.professional_registration), legal_experience_years: form.legal_experience_years || null,
                workload_capacity: form.workload_capacity || 10, availability_notes: form.availability_notes || null,
                supervisor_id: form.supervisor_id || null, start_date: form.start_date || null, contract_end_date: form.contract_end_date || null,
            }, {token});
            onSaved(response.data?.result ?? response.data);
            notify.toastSuccessMessage('Staff profile updated');
            onClose();
        } catch (error: any) {
            notify.toastErrorMessage(error?.response?.data?.message || 'Failed to update staff profile');
        } finally {
            setSaving(false);
        }
    }

    const set = (key: string, value: any) => setForm(current => ({...current, [key]: value}));

    return <Modal open={open} onClose={onClose} title="Update Staff Profile" maxWidthClassName="max-w-4xl">
        <form onSubmit={submit} className="space-y-4">
            <div><label className="ti-form-label">User account</label><input className="ti-form-input" value={`${profile?.user?.name || ''}${profile?.user?.email ? ` — ${profile.user.email}` : ''}`} disabled /></div>
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <Field label="Job title"><input className="ti-form-input" value={form.job_title} onChange={event => set('job_title', event.target.value)} /></Field>
                <Field label="Department"><select className="ti-form-input" value={form.department_id} onChange={event => set('department_id', event.target.value)}><option value="">Select department</option>{departments.map(item => <option key={item.id} value={item.id}>{item.name}</option>)}</select></Field>
                <Field label="Employment type"><select className="ti-form-input" value={form.employment_type} onChange={event => set('employment_type', event.target.value)}><option value="full_time">Full time</option><option value="part_time">Part time</option><option value="contract">Contract</option></select></Field>
                <Field label="Employment status"><select className="ti-form-input" value={form.employment_status} onChange={event => set('employment_status', event.target.value)}><option value="active">Active</option><option value="on_leave">On leave</option><option value="suspended">Suspended</option><option value="resigned">Resigned</option><option value="terminated">Terminated</option></select></Field>
                <NumberField label="Salary" value={form.salary} onChange={value => set('salary', value)} />
                <NumberField label="Hourly rate" value={form.hourly_rate} onChange={value => set('hourly_rate', value)} />
                <NumberField label="Billable rate" value={form.billable_rate} onChange={value => set('billable_rate', value)} />
                <NumberField label="Overtime rate" value={form.overtime_rate} onChange={value => set('overtime_rate', value)} />
            </div>
            <div className="border-t pt-4"><div className="mb-3 text-sm font-semibold">Legal professional and assignment profile</div><div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <TextField label="Bar admission" value={form.bar_admission} onChange={value => set('bar_admission', value)} />
                <Field label="Legal experience (years)"><input type="number" min="0" max="80" className="ti-form-input" value={form.legal_experience_years} onChange={event => set('legal_experience_years', event.target.value)} /></Field>
                <TextField label="Practice areas" value={form.practice_areas} onChange={value => set('practice_areas', value)} />
                <TextField label="Professional registrations" value={form.professional_registration} onChange={value => set('professional_registration', value)} />
                <TextField label="Qualifications / certifications" value={form.certifications} onChange={value => set('certifications', value)} />
                <TextField label="Licences" value={form.licenses} onChange={value => set('licenses', value)} />
                <TextField label="Education" value={form.education} onChange={value => set('education', value)} />
                <Field label="Workload capacity units"><input type="number" min="0.1" step="0.1" className="ti-form-input" value={form.workload_capacity} onChange={event => set('workload_capacity', event.target.value)} /></Field>
            </div>
                <label className="mt-4 flex items-center gap-2 text-sm"><input type="checkbox" checked={form.assignment_available} onChange={event => set('assignment_available', event.target.checked)} /> Available for matter assignment</label>
                <div className="mt-4"><label className="ti-form-label">Normal work schedule</label><div className="flex flex-wrap gap-3">{Object.keys(form.work_schedule).map(day => <label key={day} className="flex items-center gap-1 text-sm capitalize"><input type="checkbox" checked={Boolean(form.work_schedule[day])} onChange={event => set('work_schedule', {...form.work_schedule, [day]: event.target.checked})} />{day.slice(0, 3)}</label>)}</div></div>
                <div className="mt-4"><label className="ti-form-label">Availability notes</label><textarea rows={2} className="ti-form-input" value={form.availability_notes} onChange={event => set('availability_notes', event.target.value)} /></div>
            </div>
            <Field label="Supervisor"><select className="ti-form-input" value={form.supervisor_id} onChange={event => set('supervisor_id', event.target.value)}><option value="">No supervisor</option>{staff.filter(item => item.user_id !== profile.user_id).map(item => <option key={item.user_id} value={item.user_id}>{item.user?.name || 'Unknown staff'}</option>)}</select></Field>
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2"><Field label="Start date"><input type="date" className="ti-form-input" value={form.start_date} onChange={event => set('start_date', event.target.value)} /></Field><Field label="Contract end"><input type="date" className="ti-form-input" value={form.contract_end_date} onChange={event => set('contract_end_date', event.target.value)} /></Field></div>
            <div className="flex justify-end gap-2"><button type="button" className="ti-btn ti-btn-light px-4 py-2" onClick={onClose}>Cancel</button><button type="submit" disabled={saving} className="ti-btn ti-btn-primary px-4 py-2 disabled:opacity-40">{saving ? 'Saving...' : 'Update Profile'}</button></div>
        </form>
    </Modal>;
}

function Field({label, children}: {label: string; children: React.ReactNode}): JSX.Element { return <div><label className="ti-form-label">{label}</label>{children}</div>; }
function TextField({label, value, onChange}: {label: string; value: string; onChange: (value: string) => void}): JSX.Element { return <Field label={label}><input className="ti-form-input" value={value} onChange={event => onChange(event.target.value)} /></Field>; }
function NumberField({label, value, onChange}: {label: string; value: string; onChange: (value: string) => void}): JSX.Element { return <Field label={label}><input type="number" min="0" step="0.01" className="ti-form-input" value={value} onChange={event => onChange(event.target.value)} /></Field>; }
