'use client'

import React from 'react';
import { TimeSheetStatus } from '@alga-psa/types';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';
import { Badge } from '@alga-psa/ui/components/Badge';
import { Button } from '@alga-psa/ui/components/Button';
import { Switch } from '@alga-psa/ui/components/Switch';
import { Label } from '@alga-psa/ui/components/Label';
import { ArrowLeft, Calendar, ChevronLeft, ChevronRight, Clock, LayoutGrid, List } from 'lucide-react';
import { TimeSheetDateNavigatorState } from './types';
import ViewSwitcher, { ViewSwitcherOption } from '@alga-psa/ui/components/ViewSwitcher';

export type TimeSheetViewMode = 'grid' | 'list';

interface TimeSheetHeaderProps {
    status: TimeSheetStatus;
    isEditable: boolean;
    subjectName?: string;
    actorName?: string;
    isDelegated?: boolean;
    allowDelegatedEditing?: boolean;
    canReopenForEdits?: boolean;
    onReopenForEdits?: () => Promise<void>;
    onSubmit: () => Promise<void>;
    onBack: () => void;
    showIntervals?: boolean;
    onToggleIntervals?: () => void;
    dateNavigator?: TimeSheetDateNavigatorState | null;
    viewMode?: TimeSheetViewMode;
    onViewModeChange?: (mode: TimeSheetViewMode) => void;
}

export function TimeSheetHeader({
    status,
    isEditable,
    subjectName,
    actorName,
    isDelegated = false,
    allowDelegatedEditing = true,
    canReopenForEdits = false,
    onReopenForEdits,
    onSubmit,
    onBack,
    showIntervals = false,
    onToggleIntervals,
    dateNavigator,
    viewMode = 'grid',
    onViewModeChange
}: TimeSheetHeaderProps): React.JSX.Element {
    const { t } = useTranslation('msp/time-entry');
    // Badge variants align with TimeSheetApproval.tsx statusConfig and ManagerApprovalDashboard.tsx badgeMap
    const statusBadgeConfig: Record<string, { variant: 'outline' | 'secondary' | 'success' | 'warning'; label: string }> = {
        DRAFT: { variant: 'outline', label: t('common.states.inProgress', { defaultValue: 'In Progress' }) },
        SUBMITTED: { variant: 'secondary', label: t('common.states.submitted', { defaultValue: 'Submitted' }) },
        APPROVED: { variant: 'success', label: t('common.states.approved', { defaultValue: 'Approved' }) },
        CHANGES_REQUESTED: { variant: 'warning', label: t('common.states.changesRequested', { defaultValue: 'Changes Requested' }) },
    };
    const getStatusBadgeConfig = (s: string) =>
        statusBadgeConfig[s] ?? { variant: 'outline' as const, label: t('common.states.unknown', { defaultValue: 'Unknown' }) };

    const viewOptions: ViewSwitcherOption<TimeSheetViewMode>[] = [
        { value: 'grid', label: t('timeSheetHeader.labels.grid', { defaultValue: 'Grid' }), icon: LayoutGrid },
        { value: 'list', label: t('timeSheetHeader.labels.list', { defaultValue: 'List' }), icon: List },
    ];

    const statusDisplay = getStatusBadgeConfig(status);
    const showDelegationInfo = isDelegated && allowDelegatedEditing;

    return (
        <>
            <div className="flex flex-wrap items-center gap-x-4 gap-y-2 mb-6">
                <div className="flex items-center gap-4 min-w-0 shrink-0">
                    <Button
                        id="back-button"
                        onClick={onBack}
                        variant="soft"
                        className="shrink-0"
                    >
                        <ArrowLeft className="h-4 w-4 mr-1" /> {t('common.actions.back', { defaultValue: 'Back' })}
                    </Button>
                    <div className="min-w-0">
                        <h2 className="text-2xl font-bold truncate">
                            {showDelegationInfo && subjectName
                                ? t('timeSheetHeader.titleFor', {
                                    defaultValue: 'Time Sheet for {{name}}',
                                    name: subjectName
                                })
                                : t('timeSheetHeader.title', { defaultValue: 'Time Sheet' })}
                        </h2>
                        {showDelegationInfo && actorName && (
                            <div className="text-xs text-gray-500 truncate">
                                {t('timeSheetHeader.editedBy', {
                                    defaultValue: 'Edited by {{name}}',
                                    name: actorName
                                })}
                            </div>
                        )}
                    </div>
                </div>

                {dateNavigator?.dateRangeDisplay && (
                    <div className="flex items-center justify-center flex-1 min-w-[280px]">
                        <div className="flex items-center">
                            <div className="inline-flex items-center bg-white border border-gray-200 rounded-lg px-2 py-1.5 shadow-sm">
                                {/* Only show pagination controls in grid view */}
                                {viewMode === 'grid' && (
                                    <button
                                        onClick={dateNavigator.goToPreviousPage}
                                        disabled={!dateNavigator.canGoBack || dateNavigator.isAnimating}
                                        className={`p-1.5 rounded-md transition-colors ${
                                            dateNavigator.canGoBack && !dateNavigator.isAnimating
                                                ? 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 hover:text-gray-900 dark:hover:text-gray-100'
                                                : 'text-gray-300 cursor-not-allowed'
                                        }`}
                                        aria-label={t('timeSheetHeader.aria.previousWeek', { defaultValue: 'Previous week' })}
                                    >
                                        <ChevronLeft className="w-5 h-5" />
                                    </button>
                                )}

                                <div className="flex items-center px-3 min-w-[200px] justify-center">
                                    <Calendar className="w-4 h-4 text-gray-400 mr-2" />
                                    <span className="text-sm font-medium text-gray-900">
                                        {dateNavigator.dateRangeDisplay}
                                    </span>
                                </div>

                                {/* Only show pagination controls in grid view */}
                                {viewMode === 'grid' && (
                                    <button
                                        onClick={dateNavigator.goToNextPage}
                                        disabled={!dateNavigator.canGoForward || dateNavigator.isAnimating}
                                        className={`p-1.5 rounded-md transition-colors ${
                                            dateNavigator.canGoForward && !dateNavigator.isAnimating
                                                ? 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 hover:text-gray-900 dark:hover:text-gray-100'
                                                : 'text-gray-300 cursor-not-allowed'
                                        }`}
                                        aria-label={t('timeSheetHeader.aria.nextWeek', { defaultValue: 'Next week' })}
                                    >
                                        <ChevronRight className="w-5 h-5" />
                                    </button>
                                )}
                            </div>

                            {/* Only show page indicator in grid view */}
                            {viewMode === 'grid' && dateNavigator.hasMultiplePages && (
                                <div className="ml-3 text-xs text-gray-500 whitespace-nowrap">
                                    {t('timeSheetHeader.pagination.pageInfo', {
                                        defaultValue: 'Page {{current}} of {{total}}',
                                        current: dateNavigator.currentPage + 1,
                                        total: dateNavigator.totalPages
                                    })}
                                </div>
                            )}
                        </div>
                    </div>
                )}

                <div className="flex flex-wrap items-center justify-end gap-x-6 gap-y-2 w-full lg:w-auto lg:ml-auto">
                    <span className="text-sm font-medium flex items-center gap-2 whitespace-nowrap">
                        {t('timeSheetHeader.labels.status', { defaultValue: 'Status:' })}
                        <Badge variant={statusDisplay.variant} className="py-1">{statusDisplay.label}</Badge>
                    </span>

                    {onToggleIntervals && (
                        <div className="flex items-center gap-2 whitespace-nowrap">
                            <Switch
                                id="show-intervals-toggle"
                                checked={showIntervals}
                                onCheckedChange={onToggleIntervals}
                                data-automation-id="show-intervals-toggle"
                                data-automation-type="switch"
                            />
                            <Label htmlFor="show-intervals-toggle" className="flex items-center">
                                <Clock className="h-4 w-4 mr-1" />
                                {t('timeSheetHeader.labels.showIntervals', { defaultValue: 'Show intervals' })}
                            </Label>
                        </div>
                    )}

                    {onViewModeChange && (
                        <ViewSwitcher
                            currentView={viewMode}
                            onChange={onViewModeChange}
                            options={viewOptions}
                        />
                    )}

                    {isEditable && (
                        <Button
                            id="submit-timesheet-button"
                            onClick={onSubmit}
                            variant="default"
                            className="bg-primary-500 hover:bg-primary-600 text-white"
                        >
                            {t('common.actions.submitTimeSheet', { defaultValue: 'Submit Time Sheet' })}
                        </Button>
                    )}

                    {!isEditable && status === 'APPROVED' && canReopenForEdits && onReopenForEdits && (
                        <Button
                            id="reopen-timesheet-button"
                            onClick={onReopenForEdits}
                            variant="soft"
                        >
                            {t('common.actions.reopenForEdits', { defaultValue: 'Reopen for edits' })}
                        </Button>
                    )}
                </div>
            </div>
        </>
    );
}
