'use client';

import { useState, useEffect } from 'react';
import { Download, X, FileText, CheckCircle } from 'lucide-react';
import { usePhoneStore } from '@/store/sqliteStore';
import { useUIStore } from '@/store/uiStore';
import { Phone } from '@/types/phone';
import { toast } from 'react-hot-toast';

interface ExportCSVModalProps {
    onClose: () => void;
}

export default function ExportCSVModal({ onClose }: ExportCSVModalProps) {
    const { phones, filteredPhones } = usePhoneStore();
    const { addNotification } = useUIStore();
    const [isExporting, setIsExporting] = useState(false);
    const [exportType, setExportType] = useState<'all' | 'filtered'>('all');

    const convertToCSV = (data: Phone[]) => {
        if (data.length === 0) return '';

        const headers = [
            'phone',
            'domain',
            'website',
            'owner',
            'email',
            'package',
            'amount',
            'status',
            'priority',
            'nextPayment',
            'notes',
            'createdAt',
            'updatedAt'
        ];

        const csvContent = [
            headers.join(','),
            ...data.map(phone => [
                `"${phone.phone}"`,
                `"${phone.domain}"`,
                `"${phone.website || ''}"`,
                `"${phone.owner}"`,
                `"${phone.email}"`,
                `"${phone.package}"`,
                phone.amount,
                `"${phone.status}"`,
                `"${phone.priority}"`,
                `"${phone.nextPayment}"`,
                `"${phone.notes || ''}"`,
                `"${phone.createdAt}"`,
                `"${phone.updatedAt}"`
            ].join(','))
        ].join('\n');

        return csvContent;
    };

    const downloadCSV = (csvContent: string, filename: string) => {
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        link.click();
    };

    const handleExport = async () => {
        setIsExporting(true);

        try {
            const dataToExport = exportType === 'all' ? phones : filteredPhones;

            if (dataToExport.length === 0) {
                toast.error('אין נתונים לייצוא');
                setIsExporting(false);
                return;
            }

            const csvContent = convertToCSV(dataToExport);
            const timestamp = new Date().toISOString().split('T')[0];
            const filename = `phones_${exportType === 'all' ? 'all' : 'filtered'}_${timestamp}.csv`;

            downloadCSV(csvContent, filename);

            toast.success(`${dataToExport.length} דומיינים יוצאו בהצלחה!`);
            addNotification({
                type: 'success',
                title: 'ייצוא CSV',
                message: `${dataToExport.length} דומיינים יוצאו לקובץ ${filename}`,
                duration: 5000,
                timestamp: new Date(),
            });

            // Close modal immediately after successful export
            onClose();
        } catch (error) {
            console.error('Error exporting CSV:', error);
            toast.error('שגיאה בייצוא הקובץ');
        } finally {
            setIsExporting(false);
        }
    };

    const exportStats = {
        all: phones.length,
        filtered: filteredPhones.length
    };

    // Close modal on Escape key
    useEffect(() => {
        const handleEscape = (event: KeyboardEvent) => {
            if (event.key === 'Escape') {
                onClose();
            }
        };

        document.addEventListener('keydown', handleEscape);
        return () => document.removeEventListener('keydown', handleEscape);
    }, [onClose]);

    return (
        <div
            className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
            onClick={onClose}
        >
            <div
                className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4"
                onClick={(e) => e.stopPropagation()}
            >
                <div className="flex items-center justify-between p-6 border-b border-gray-200">
                    <div className="flex items-center">
                        <Download className="w-6 h-6 text-blue-600 ml-3" />
                        <h2 className="text-xl font-semibold text-gray-900">ייצוא דומיינים ל-CSV</h2>
                    </div>
                    <button
                        onClick={onClose}
                        className="text-gray-400 hover:text-gray-600"
                        title="סגור"
                        aria-label="סגור חלון ייצוא CSV"
                    >
                        <X className="w-6 h-6" />
                    </button>
                </div>

                <div className="p-6">
                    <div className="space-y-4">
                        <div className="text-center">
                            <div className="mx-auto w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mb-4">
                                <FileText className="w-6 h-6 text-blue-600" />
                            </div>
                            <h3 className="text-lg font-medium text-gray-900 mb-2">
                                בחר איזה דומיינים לייצא
                            </h3>
                        </div>

                        <div className="space-y-3">
                            <label className="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50">
                                <input
                                    type="radio"
                                    name="exportType"
                                    value="all"
                                    checked={exportType === 'all'}
                                    onChange={(e) => setExportType(e.target.value as 'all')}
                                    className="ml-3"
                                />
                                <div className="flex-1">
                                    <div className="flex items-center justify-between">
                                        <span className="text-sm font-medium text-gray-900">כל הדומיינים</span>
                                        <span className="text-sm text-gray-500">{exportStats.all} דומיינים</span>
                                    </div>
                                </div>
                            </label>

                            <label className="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50">
                                <input
                                    type="radio"
                                    name="exportType"
                                    value="filtered"
                                    checked={exportType === 'filtered'}
                                    onChange={(e) => setExportType(e.target.value as 'filtered')}
                                    className="ml-3"
                                />
                                <div className="flex-1">
                                    <div className="flex items-center justify-between">
                                        <span className="text-sm font-medium text-gray-900">דומיינים מסוננים</span>
                                        <span className="text-sm text-gray-500">{exportStats.filtered} דומיינים</span>
                                    </div>
                                </div>
                            </label>
                        </div>

                        <div className="bg-gray-50 rounded-lg p-4">
                            <div className="flex items-center">
                                <CheckCircle className="w-5 h-5 text-green-500 ml-2" />
                                <span className="text-sm text-gray-700">
                                    הקובץ יכלול את כל השדות: פלאפון, דומיין, אתר, בעלים, אימייל, חבילה, סכום, סטטוס, עדיפות, תאריך תשלום הבא
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div className="flex items-center justify-end space-x-3 space-x-reverse p-6 border-t border-gray-200">
                    <button
                        onClick={onClose}
                        className="px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                    >
                        ביטול
                    </button>
                    <button
                        onClick={handleExport}
                        disabled={isExporting || (exportType === 'all' ? phones.length === 0 : filteredPhones.length === 0)}
                        className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                        <Download className="w-4 h-4 ml-2" />
                        {isExporting ? 'מייצא...' : 'ייצא CSV'}
                    </button>
                </div>
            </div>
        </div>
    );
}
