import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { Modal } from '@/components/ui/modal';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { useState } from 'react';

interface BulkExportModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    selectedUsers: any[]; // Make it generic to accept any array of objects with id
    onSuccess?: () => void;
    config: {
        route: string;
        payload: object;
    };
    handleColumnChange: (columnValue: string, checked: boolean) => void;
    selectedColumns: string[];
    title?: string; // Optional custom title
    itemName?: string; // Optional custom item name (e.g., "users", "activities")
    availableColumns?: Array<{ value: string; label: string; description: string }>; // Optional custom columns
    selectAll?: boolean;
    currentFilters?: Record<string, any>;
    totalCount?: number;
}

const EXPORT_FORMATS = [
    { value: 'csv', label: 'CSV', description: 'Comma-separated values' },
    { value: 'pdf', label: 'PDF', description: 'Portable document format' },
];

const AVAILABLE_COLUMNS = [
    { value: 'uid', label: 'Uid', description: 'User unique identifier' },
    { value: 'name', label: 'Name', description: 'User full name' },
    { value: 'email', label: 'Email', description: 'User email address' },
    { value: 'phone', label: 'Phone', description: 'User phone number' },
    { value: 'role', label: 'Role', description: 'User role/permissions' },
    { value: 'status', label: 'Status', description: 'User account status' },
    { value: 'created_at', label: 'Created At', description: 'Account creation date' },
    { value: 'updated_at', label: 'Updated At', description: 'Last update date' },
];

export function BulkExportModal({
    open,
    onOpenChange,
    selectedUsers,
    onSuccess,
    config,
    handleColumnChange,
    selectedColumns,
    title = 'Export Data',
    itemName = 'items',
    availableColumns,
    selectAll = false,
    currentFilters = {},
    totalCount,
}: BulkExportModalProps) {
    const [selectedFormat, setSelectedFormat] = useState<string>('csv');
    const [isLoading, setIsLoading] = useState(false);

    // Use custom columns or default user columns
    const COLUMNS_TO_USE = availableColumns || AVAILABLE_COLUMNS;

    const handleSelectAllColumns = () => {
        const shouldSelectAll = selectedColumns.length !== COLUMNS_TO_USE.length;

        COLUMNS_TO_USE.forEach((column) => {
            const isCurrentlySelected = selectedColumns.includes(column.value);

            if (shouldSelectAll && !isCurrentlySelected) {
                handleColumnChange(column.value, true);
            } else if (!shouldSelectAll && isCurrentlySelected) {
                handleColumnChange(column.value, false);
            }
        });
    };

    const handleSubmit = async () => {
        if (!selectedFormat || selectedColumns.length === 0 || selectedUsers.length === 0) return;

        setIsLoading(true);
        try {
            const ids = selectedUsers.map((u: any) => u.id);
            const isBulk = !!(config?.payload as any)?.type; // bulk-action has explicit type

            let payload: any;
            if (isBulk) {
                payload = {
                    ...config.payload,
                    type: 'export',
                    data: {
                        ...(config.payload as any)?.data,
                        columns: selectedColumns,
                        format: selectedFormat,
                    },
                };
                if (selectAll) {
                    payload.select_all = true;
                    payload.filters = currentFilters;
                } else {
                    payload.ids = ids;
                }
            } else {
                // direct export expects root level columns & format only
                payload = {
                    columns: selectedColumns,
                    format: selectedFormat,
                };
            }

            const csrfToken = (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content;
            if (!csrfToken) throw new Error('CSRF token not found');

            const response = await fetch(route(config.route), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken,
                    'X-Requested-With': 'XMLHttpRequest',
                    Accept: 'application/json',
                },
                body: JSON.stringify(payload),
            });

            if (!response.ok) {
                const text = await response.text();

                // Handle CSRF token mismatch specifically
                if (response.status === 419) {
                    alert('Your session has expired. Please refresh the page and try again.');
                    window.location.reload();
                    return;
                }

                throw new Error(`Request failed with status ${response.status}: ${text}`);
            }

            const data = await response.json();
            if (data?.export?.file_url) {
                window.open(data.export.file_url, '_blank');
            }
            onOpenChange(false);
            onSuccess?.();
        } catch (e) {
            console.error('Error exporting users:', e);
            alert(`Export failed: ${e instanceof Error ? e.message : 'Unknown error'}`);
        } finally {
            setIsLoading(false);
        }
    };

    const isSubmitDisabled = selectedColumns.length === 0 || isLoading;

    const handleCancel = () => {
        onOpenChange(false);
    };

    const selectedFormatOption = EXPORT_FORMATS.find((format) => format.value === selectedFormat);

    return (
        <Modal
            open={open}
            onOpenChange={onOpenChange}
            title={title}
            description={
                selectAll
                    ? `Export ALL ${totalCount ?? selectedUsers.length} matched ${itemName}`
                    : `Export ${selectedUsers.length} selected ${itemName}${selectedUsers.length > 1 ? 's' : ''} to file`
            }
            size="xl"
            footer={
                <>
                    <Button variant="outline" onClick={handleCancel} disabled={isLoading}>
                        Cancel
                    </Button>
                    <Button className="bg-success hover:bg-brand-800" onClick={handleSubmit} disabled={isSubmitDisabled} variant="default">
                        {isLoading ? 'Exporting...' : 'Export'}
                    </Button>
                </>
            }
        >
            <div className="space-y-6">
                {/* Format Selection */}
                <div className="space-y-6">
                    <Label className="text-sm font-bold">Export Format</Label>
                    <RadioGroup value={selectedFormat} onValueChange={setSelectedFormat} className="grid grid-cols-2 gap-4">
                        {EXPORT_FORMATS.map((format) => (
                            <div key={format.value} className="flex items-center space-x-2 pt-2">
                                <RadioGroupItem value={format.value} id={format.value} />
                                <div className="grid gap-1.5 leading-none">
                                    <Label
                                        htmlFor={format.value}
                                        className="text-sm leading-none font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                                    >
                                        {format.label}
                                    </Label>
                                    {/* <p className="text-xs text-muted-foreground">{format.description}</p> */}
                                </div>
                            </div>
                        ))}
                    </RadioGroup>
                </div>

                {/* Column Selection */}
                <div className="space-y-3">
                    <div className="flex items-center justify-between">
                        <Label className="text-sm font-bold">Columns to Export</Label>
                        <button type="button" onClick={handleSelectAllColumns} className="text-xs font-semibold text-primary hover:underline">
                            {selectedColumns.length === COLUMNS_TO_USE.length ? 'Deselect All' : 'Select All'}
                        </button>
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                        {COLUMNS_TO_USE.map((column) => (
                            <div key={column.value} className="flex items-start space-x-2">
                                <Checkbox
                                    id={column.value}
                                    checked={selectedColumns.includes(column.value)}
                                    onCheckedChange={(checked) => handleColumnChange(column.value, !!checked)}
                                />
                                <div className="grid gap-1.5 leading-none">
                                    <Label
                                        htmlFor={column.value}
                                        className="text-sm leading-none font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                                    >
                                        {column.label}
                                    </Label>
                                    {/* <p className="text-xs text-muted-foreground">{column.description}</p> */}
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        </Modal>
    );
}
