import React, {ReactNode, useEffect, useState} from 'react';
import {Link, usePage} from '@inertiajs/react';
import MainLayout from '@/layouts/MainLayout';
import AppPageHeader from '@/components/AppPageHeader';
import BranchDetails from '@/components/BranchDetails';
import {makeGetRequest} from '@/lib/request';
import {notify} from '@/lib/notify';
import {hasPermission} from '@/lib/user-helper';
import StaffProfileEditModal from './StaffProfileEditModal';

const titleCase = (value?: string | null): string => String(value || '—').replaceAll('_', ' ').replace(/\b\w/g, character => character.toUpperCase());
const dateLabel = (value?: string | null): string => value ? new Date(value).toLocaleDateString() : '—';
const money = (value?: string | number | null): string => value == null || value === '' ? '—' : Number(value).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
const initials = (name?: string | null): string => String(name || 'Staff').split(/\s+/).slice(0, 2).map(part => part[0]).join('').toUpperCase();

type ProfileTab = 'employment' | 'professional' | 'workload' | 'schedule' | 'assignments' | 'leave' | 'payroll';
const PROFILE_TABS: Array<{key: ProfileTab; label: string; icon: string}> = [
    {key: 'employment', label: 'Employment', icon: 'fa fa-briefcase'},
    {key: 'professional', label: 'Professional', icon: 'fa fa-graduation-cap'},
    {key: 'workload', label: 'Workload', icon: 'fa fa-tasks'},
    {key: 'schedule', label: 'Schedule', icon: 'fa fa-calendar'},
    {key: 'assignments', label: 'Assignments', icon: 'fa fa-folder-open'},
    {key: 'leave', label: 'Leave', icon: 'fa fa-plane'},
    {key: 'payroll', label: 'Payroll', icon: 'fa fa-money'},
];

export default function Show({profileId}: {profileId: number}): JSX.Element {
    const {auth} = usePage<{auth: {user: any}}>().props;
    const token = auth?.user?.api_token ?? auth?.user?.token;
    const [profile, setProfile] = useState<any | null>(null);
    const [workload, setWorkload] = useState<any | null>(null);
    const [loading, setLoading] = useState(true);
    const [activeTab, setActiveTab] = useState<ProfileTab>('employment');
    const [editOpen, setEditOpen] = useState(false);
    const canUpdate = hasPermission(auth?.user, 'staff_update');

    useEffect(() => {
        setLoading(true);
        makeGetRequest(`/api/hr/staff/${profileId}`, {token})
            .then(response => {
                const payload = response.data?.result ?? response.data ?? {};
                setProfile(payload.profile ?? null);
                setWorkload(payload.workload ?? null);
            })
            .catch(error => notify.toastErrorMessage(error?.response?.data?.message || 'Unable to load staff profile'))
            .finally(() => setLoading(false));
    }, [profileId, token]);

    if (loading) return <MainLayout><AppPageHeader title="Staff Profile" subtitle="HR & Payroll" /><div className="box"><div className="box-body py-12 text-center text-gray-500">Loading staff profile…</div></div></MainLayout>;
    if (!profile) return <MainLayout><AppPageHeader title="Staff Profile" subtitle="HR & Payroll" /><div className="box"><div className="box-body py-12 text-center text-gray-500">Staff profile not found.</div></div></MainLayout>;

    const user = profile.user ?? {};
    const branch = user.branch ?? profile.branch;
    const schedule = profile.work_schedule ?? {};
    const assignments = profile.matter_assignments ?? [];
    const leaveRequests = profile.leave_requests ?? [];
    const payrollRecords = profile.payroll_records ?? [];

    return (
        <MainLayout>
            <AppPageHeader title="Staff Profile" subtitle="HR & Payroll" />

            <div className="mb-4">
                <Link href="/payroll" className="inline-flex items-center gap-2 text-sm text-indigo-600 hover:underline"><i className="fa fa-arrow-left" />Back to staff directory</Link>
            </div>

            <div className="box">
                <div className="box-body flex flex-col gap-5 md:flex-row md:items-center">
                    <div className="flex h-20 w-20 shrink-0 items-center justify-center rounded-full border-2 border-indigo-200 bg-indigo-50 text-2xl font-semibold text-indigo-600">{initials(user.name)}</div>
                    <div className="min-w-0 flex-1">
                        <div className="flex flex-wrap items-center gap-3">
                            <h2 className="text-2xl font-semibold text-gray-900 dark:text-white">{user.name || 'Unknown staff member'}</h2>
                            <StatusBadge status={profile.employment_status} />
                        </div>
                        <div className="mt-1 text-gray-500">{profile.job_title || 'No job title'} · {profile.department_record?.name || profile.department || 'No department'}</div>
                        <div className="mt-3 flex flex-wrap gap-x-5 gap-y-2 text-sm text-gray-500">
                            <span><i className="fa fa-envelope mr-2" />{user.email || 'No email'}</span>
                            <span><i className="fa fa-building mr-2" />{branch?.name || 'No branch'}</span>
                            <span><i className="fa fa-user mr-2" />Supervisor: {profile.supervisor?.name || 'Not assigned'}</span>
                        </div>
                    </div>
                    {canUpdate ? <button type="button" className="ti-btn ti-btn-light shrink-0" onClick={() => setEditOpen(true)}><i className="fa fa-pencil mr-2" />Edit</button> : null}
                </div>
            </div>

            <div className="box">
                <div className="overflow-x-auto border-b border-gray-200 dark:border-gray-700">
                    <nav className="flex min-w-max px-3" role="tablist" aria-label="Staff profile sections">
                        {PROFILE_TABS.map(tab => (
                            <button
                                key={tab.key}
                                type="button"
                                role="tab"
                                aria-selected={activeTab === tab.key}
                                onClick={() => setActiveTab(tab.key)}
                                className={`border-b-2 px-4 py-4 text-sm font-medium transition-colors ${activeTab === tab.key ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-800 dark:hover:text-gray-200'}`}
                            >
                                <i className={`${tab.icon} mr-2`} />{tab.label}
                            </button>
                        ))}
                    </nav>
                </div>
            </div>

            {activeTab === 'employment' ? (
                <DetailCard title="Employment Details">
                    <DetailGrid>
                        <Detail label="Employee" value={user.name} />
                        <Detail label="Email" value={user.email} />
                        <Detail label="Job title" value={profile.job_title} />
                        <Detail label="Department" value={profile.department_record?.name || profile.department} />
                        <Detail label="Employment type" value={titleCase(profile.employment_type)} />
                        <Detail label="Employment status" value={titleCase(profile.employment_status)} />
                        <Detail label="Start date" value={dateLabel(profile.start_date)} />
                        <Detail label="Contract end" value={dateLabel(profile.contract_end_date)} />
                        <Detail label="Supervisor" value={profile.supervisor?.name} />
                        <div><div className="text-xs uppercase tracking-wide text-gray-400">Branch</div><div className="mt-1"><BranchDetails branch={branch} /></div></div>
                    </DetailGrid>
                </DetailCard>
            ) : null}

            {activeTab === 'professional' ? (
                <DetailCard title="Professional Profile">
                    <DetailGrid>
                        <Detail label="Bar admission" value={profile.bar_admission} />
                        <Detail label="Legal experience" value={profile.legal_experience_years == null ? '—' : `${profile.legal_experience_years} year(s)`} />
                        <Detail label="System roles" value={(user.roles ?? []).map((role: any) => role.name).join(', ')} />
                        <Detail label="Professional registration" value={listLabel(profile.professional_registration)} />
                    </DetailGrid>
                    <TagSection label="Practice areas" values={profile.practice_areas} />
                    <TagSection label="Qualifications / certifications" values={profile.certifications} />
                    <TagSection label="Licences" values={profile.licenses} />
                    <TagSection label="Education" values={profile.education} />
                </DetailCard>
            ) : null}

            {activeTab === 'workload' ? (
                <DetailCard title="Assignment Availability & Workload">
                    <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
                        <Metric label="Active matters" value={workload?.active_matter_count ?? 0} />
                        <Metric label="Lead assignments" value={workload?.lead_assignments ?? 0} />
                        <Metric label="Supporting assignments" value={workload?.supporting_assignments ?? 0} />
                        <Metric label="Outstanding tasks" value={workload?.outstanding_tasks ?? 0} />
                        <Metric label="Upcoming deadlines" value={workload?.upcoming_deadlines ?? 0} />
                        <Metric label="Court commitments" value={workload?.upcoming_court_commitments ?? 0} />
                        <Metric label="Used capacity" value={`${workload?.used_capacity ?? 0}/${workload?.capacity ?? profile.workload_capacity ?? 0}`} />
                        <Metric label="Utilization" value={`${workload?.capacity_utilization ?? 0}%`} />
                    </div>
                    <div className="mt-4 rounded-lg border border-gray-200 p-4 dark:border-gray-700">
                        <div className="flex items-center justify-between gap-3"><span className="font-medium">Assignment availability</span><span className={profile.assignment_available ? 'text-success' : 'text-danger'}>{profile.assignment_available ? 'Available' : 'Unavailable'}</span></div>
                        <p className="mt-2 text-sm text-gray-500">{profile.availability_notes || 'No availability notes recorded.'}</p>
                    </div>
                </DetailCard>
            ) : null}

            {activeTab === 'schedule' ? (
                <DetailCard title="Normal Work Schedule">
                    <div className="grid grid-cols-1 gap-2 md:grid-cols-2 xl:grid-cols-3">
                        {Object.keys(schedule).length ? Object.entries(schedule).map(([day, available]) => <div key={day} className="flex items-center justify-between rounded border border-gray-100 px-3 py-3 dark:border-gray-700"><span>{titleCase(day)}</span><span className={available ? 'text-success' : 'text-gray-400'}>{available ? 'Working' : 'Off'}</span></div>) : <div className="text-sm text-gray-500">No work schedule recorded.</div>}
                    </div>
                    <TagSection label="Emergency contacts" values={profile.emergency_contacts} />
                </DetailCard>
            ) : null}

            {activeTab === 'assignments' ? (
                <DetailCard title="Matter Assignment History">
                    <div className="rounded-sm overflow-auto todo-table w-full">
                        <table className="ti-custom-table ti-custom-table-head whitespace-nowrap w-full">
                            <thead className="bg-gray-100 dark:bg-bodybg"><tr><th>Matter</th><th>Client</th><th>Role</th><th>Responsibility</th><th>Effective period</th><th>Status</th></tr></thead>
                            <tbody>{assignments.length ? assignments.map((assignment: any) => <tr key={assignment.id}><td>{assignment.matter ? <Link href={`/matters/${assignment.matter.id}`} className="font-semibold text-indigo-600 hover:underline">{assignment.matter.reference_number}</Link> : '—'}</td><td>{assignment.matter?.client?.name || '—'}</td><td>{assignment.role || '—'}</td><td>{assignment.responsibility || '—'}</td><td>{dateLabel(assignment.effective_from)} – {assignment.effective_to ? dateLabel(assignment.effective_to) : 'Present'}</td><td><StatusBadge status={assignment.status} /></td></tr>) : <tr><td colSpan={6} className="py-8 text-center text-gray-500">No matter assignments recorded.</td></tr>}</tbody>
                        </table>
                    </div>
                </DetailCard>
            ) : null}

            {activeTab === 'leave' ? (
                <DetailCard title="Leave History">
                    <div className="rounded-sm overflow-auto todo-table w-full"><table className="ti-custom-table ti-custom-table-head whitespace-nowrap w-full"><thead className="bg-gray-100 dark:bg-bodybg"><tr><th>Type</th><th>Period</th><th>Status</th><th>Decision</th></tr></thead><tbody>{leaveRequests.length ? leaveRequests.map((request: any) => <tr key={request.id}><td>{titleCase(request.leave_type)}</td><td>{dateLabel(request.start_date)} – {dateLabel(request.end_date)}</td><td><StatusBadge status={request.status} /></td><td>{request.approved_by?.name || '—'}</td></tr>) : <tr><td colSpan={4} className="py-8 text-center text-gray-500">No leave history recorded.</td></tr>}</tbody></table></div>
                </DetailCard>
            ) : null}

            {activeTab === 'payroll' ? (
                <DetailCard title="Payroll History">
                    <div className="rounded-sm overflow-auto todo-table w-full"><table className="ti-custom-table ti-custom-table-head whitespace-nowrap w-full"><thead className="bg-gray-100 dark:bg-bodybg"><tr><th>Period</th><th>Gross</th><th>Tax</th><th>Net</th><th>Status</th></tr></thead><tbody>{payrollRecords.length ? payrollRecords.map((record: any) => <tr key={record.id}><td>{dateLabel(record.period_start)} – {dateLabel(record.period_end)}</td><td>{money(record.gross_pay)}</td><td>{money(record.tax_amount)}</td><td className="font-medium">{money(record.net_pay)}</td><td><StatusBadge status={record.status} /></td></tr>) : <tr><td colSpan={5} className="py-8 text-center text-gray-500">No payroll history recorded.</td></tr>}</tbody></table></div>
                </DetailCard>
            ) : null}

            <StaffProfileEditModal open={editOpen} profile={profile} token={token} onClose={() => setEditOpen(false)} onSaved={updated => setProfile((current: any) => ({...current, ...updated}))} />
        </MainLayout>
    );
}

function DetailCard({title, children, className = ''}: {title: string; children: ReactNode; className?: string}): JSX.Element {
    return <div className={`box ${className}`}><div className="box-header"><h3 className="box-title">{title}</h3></div><div className="box-body">{children}</div></div>;
}

function DetailGrid({children}: {children: ReactNode}): JSX.Element {
    return <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">{children}</div>;
}

function Detail({label, value}: {label: string; value?: ReactNode}): JSX.Element {
    return <div><div className="text-xs uppercase tracking-wide text-gray-400">{label}</div><div className="mt-1 text-sm font-medium text-gray-800 dark:text-gray-100">{value || '—'}</div></div>;
}

function Metric({label, value}: {label: string; value: ReactNode}): JSX.Element {
    return <div className="rounded-lg border border-gray-200 p-3 dark:border-gray-700"><div className="text-xs text-gray-500">{label}</div><div className="mt-1 text-lg font-semibold">{value}</div></div>;
}

function StatusBadge({status}: {status?: string | null}): JSX.Element {
    const normalized = String(status || '').toLowerCase();
    const tone = ['active', 'approved', 'paid', 'completed'].includes(normalized) ? 'bg-success/10 text-success' : ['terminated', 'denied', 'rejected', 'ended'].includes(normalized) ? 'bg-danger/10 text-danger' : 'bg-warning/10 text-warning';
    return <span className={`badge ${tone}`}>{titleCase(status)}</span>;
}

function TagSection({label, values}: {label: string; values?: any[] | null}): JSX.Element {
    const items = Array.isArray(values) ? values : [];
    return <div className="mt-4"><div className="mb-2 text-xs uppercase tracking-wide text-gray-400">{label}</div><div className="flex flex-wrap gap-2">{items.length ? items.map((value, index) => <span key={`${label}-${index}`} className="badge bg-primary/10 text-primary">{typeof value === 'object' ? Object.values(value).filter(Boolean).join(' · ') : String(value)}</span>) : <span className="text-sm text-gray-500">None recorded</span>}</div></div>;
}

function listLabel(values?: any[] | null): string {
    if (!Array.isArray(values) || !values.length) return '—';
    return values.map(value => typeof value === 'object' ? Object.values(value).filter(Boolean).join(' · ') : String(value)).join(', ');
}
