'use client';

import { useState, useRef, useEffect } from 'react';
import { Upload, X, FileText, AlertCircle, 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';
import * as XLSX from 'xlsx';

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

interface CSVRow {
    phone: string;
    domain: string;
    website?: string;
    owner: string;
    email: string;
    package: string;
    amount: string;
    status: string;
    priority: string;
    nextPayment: string;
    notes?: string;
}

export default function ImportCSVModal({ onClose }: ImportCSVModalProps) {
    const { addPhone } = usePhoneStore();
    const { addNotification } = useUIStore();
    const [isProcessing, setIsProcessing] = useState(false);
    const [previewData, setPreviewData] = useState<CSVRow[]>([]);
    const [showPreview, setShowPreview] = useState(false);
    const fileInputRef = useRef<HTMLInputElement>(null);

    const normalizeStatus = (value: string): string => {
        const v = (value || '').trim();
        // Hebrew/aliases → internal keys
        const map: Record<string, string> = {
            'לחידוש': 'renewal',
            'למחוק': 'delete_backup',
            'חינם': 'free',
            'פעיל': 'paid',
            'מושהה': 'paused',
        };
        return map[v] || v.toLowerCase();
    };

    const parseDate = (value: string): string => {
        // Accept dd/MM/yyyy or yyyy-MM-dd; return yyyy-MM-dd
        const s = (value || '').trim();
        if (/^\d{4}-\d{2}-\d{2}T/.test(s)) {
            return s; // full ISO timestamp (used for createdAt)
        }
        if (/^\d{2}\/\d{2}\/\d{4}$/.test(s)) {
            const [dd, mm, yyyy] = s.split('/');
            return `${yyyy}-${mm.padStart(2, '0')}-${dd.padStart(2, '0')}`;
        }
        // Fallback to Date parsing
        const d = new Date(s);
        if (!isNaN(d.getTime())) {
            return d.toISOString().slice(0, 10);
        }
        return new Date().toISOString().slice(0, 10);
    };

    const splitCSVLine = (line: string, delimiter: ',' | '\t' = ','): string[] => {
        const result: string[] = [];
        let current = '';
        let inQuotes = false;
        for (let i = 0; i < line.length; i++) {
            const ch = line[i];
            if (ch === '"' && delimiter === ',') {
                if (inQuotes && line[i + 1] === '"') { current += '"'; i++; }
                else { inQuotes = !inQuotes; }
            } else if (ch === delimiter && !inQuotes) {
                result.push(current);
                current = '';
            } else {
                current += ch;
            }
        }
        result.push(current);
        return result.map(v => v.trim());
    };

    const parseCSV = (csvText: string): CSVRow[] => {
        const lines = csvText.split('\n').filter(line => line.trim());
        if (lines.length < 2) return [];

        // Detect delimiter: prefer tab if present in header
        const delimiter: ',' | '\\t' = lines[0].includes('\t') ? '\t' : ',';
        const rawHeaders = splitCSVLine(lines[0], delimiter).map(h => h.replace(/"/g, ''));
        const normalizeHeader = (h: string) => h
            .replace(/\uFEFF/g, '')
            .trim()
            .toLowerCase()
            .replace(/\s+/g, '_');
        const headerAliases: Record<string, string> = {
            'תאריך_התחלה': 'startdate',
            'start_date': 'startdate',
            'startdate': 'startdate',
            'nextpayment': 'nextpayment',
            // createdAt stays a separate optional field
            'createdat': 'createdat',
            'נוצר_בתאריך': 'createdat',
        };
        const headers = rawHeaders.map(h => headerAliases[normalizeHeader(h)] || normalizeHeader(h));
        const rows: CSVRow[] = [];

        for (let i = 1; i < lines.length; i++) {
            const values = splitCSVLine(lines[i], delimiter).map(v => v.replace(/"/g, ''));

            // Normalize amount: remove currency symbols, spaces and thousands separators
            const rawAmount = (values[6] || '').toString();
            const normalizedAmount = rawAmount
                .replace(/[^0-9,\.\-]/g, '') // keep digits, comma, dot, minus
                .replace(/,(?=\d{3}(?:\D|$))/g, '') // remove thousands commas (1,000 -> 1000)
                .replace(',', '.'); // convert decimal comma to dot
            if (values.length >= rawHeaders.length) {
                // Helper to read by header name with fallbacks
                const idx = (name: string, altNames: string[] = []): number => {
                    const names = [name, ...altNames];
                    for (const n of names) {
                        const i = headers.indexOf(n);
                        if (i !== -1) return i;
                    }
                    return -1;
                };

                const phoneIdx = idx('phone');
                const domainIdx = idx('domain');
                const websiteIdx = idx('website');
                const ownerIdx = idx('owner');
                const emailIdx = idx('email');
                const packageIdx = idx('package');
                const amountIdx = idx('amount');
                const statusIdx = idx('status');
                const priorityIdx = idx('priority');
                const startDateIdx = idx('startdate', ['תאריך_התחלה']);
                const nextPaymentIdx = idx('nextpayment');
                const createdAtIdx = idx('createdat');
                const notesIdx = idx('notes');

                const row: CSVRow = {
                    phone: (phoneIdx >= 0 ? values[phoneIdx] : values[0]) || '',
                    domain: (domainIdx >= 0 ? values[domainIdx] : values[1]) || '',
                    website: (websiteIdx >= 0 ? values[websiteIdx] : values[2]) || '',
                    owner: (ownerIdx >= 0 ? values[ownerIdx] : values[3]) || '',
                    email: (emailIdx >= 0 ? values[emailIdx] : values[4]) || '',
                    package: (packageIdx >= 0 ? values[packageIdx] : values[5]) || 'Linux Mini',
                    amount: (amountIdx >= 0 ? (values[amountIdx] || '') : normalizedAmount) || '0',
                    status: normalizeStatus((statusIdx >= 0 ? values[statusIdx] : values[7]) || 'pending'),
                    priority: (priorityIdx >= 0 ? values[priorityIdx] : values[8]) || 'medium',
                    nextPayment: parseDate((nextPaymentIdx >= 0 ? values[nextPaymentIdx] : values[9]) || new Date().toISOString().split('T')[0]),
                    notes: (notesIdx >= 0 ? values[notesIdx] : values[10]) || ''
                };

                // Attach startDate separately so we can use exact field in addPhone call
                // @ts-ignore - enrich row
                (row as any)._startDateParsed = startDateIdx >= 0 ? parseDate(values[startDateIdx] || new Date().toISOString().slice(0, 10)) : undefined;
                (row as any)._createdAtParsed = createdAtIdx >= 0 ? parseDate(values[createdAtIdx]) : undefined;
                rows.push(row);
            }
        }

        return rows;
    };

    const validateCSVData = (data: CSVRow[]): { valid: CSVRow[]; invalid: CSVRow[] } => {
        const valid: CSVRow[] = [];
        const invalid: CSVRow[] = [];

        data.forEach(row => {
            const isValid =
                row.domain &&
                row.owner &&
                row.email &&
                !isNaN(Number(row.amount)) &&
                ['pending', 'paid', 'overdue', 'free', 'paused', 'delete_backup', 'delete_no_backup', 'renewal'].includes(row.status) &&
                ['low', 'medium', 'high', 'to-delete', 'to-check'].includes(row.priority);

            if (isValid) {
                valid.push(row);
            } else {
                invalid.push(row);
            }
        });

        return { valid, invalid };
    };

    const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        if (!file) return;

        const lower = file.name.toLowerCase();
        if (!lower.endsWith('.csv') && !lower.endsWith('.tsv') && !lower.endsWith('.xlsx')) {
            toast.error('אנא בחר קובץ CSV / TSV / XLSX');
            return;
        }

        const reader = new FileReader();
        reader.onload = (e) => {
            const buffer = e.target?.result as ArrayBuffer | string;

            let rows: CSVRow[] = [];
            const name = file.name.toLowerCase();
            try {
                if (name.endsWith('.xlsx')) {
                    const workbook = XLSX.read(buffer, { type: 'array' });
                    const sheetName = workbook.SheetNames[0];
                    const sheet = workbook.Sheets[sheetName];
                    const csvText = XLSX.utils.sheet_to_csv(sheet);
                    rows = parseCSV(csvText);
                } else {
                    const text = typeof buffer === 'string' ? buffer : new TextDecoder('utf-8').decode(buffer as ArrayBuffer);
                    rows = parseCSV(text);
                }
            } catch {
                toast.error('שגיאה בקריאת הקובץ');
                return;
            }

            if (rows.length === 0) {
                toast.error('לא נמצאו נתונים תקינים בקובץ');
                return;
            }

            setPreviewData(rows);
            setShowPreview(true);
        };
        if (file.name.toLowerCase().endsWith('.xlsx')) reader.readAsArrayBuffer(file);
        else reader.readAsText(file, 'utf-8');
    };

    const handleImport = async () => {
        if (previewData.length === 0) return;

        setIsProcessing(true);
        const { valid, invalid } = validateCSVData(previewData);

        if (invalid.length > 0) {
            toast.error(`${invalid.length} שורות לא תקינות נדחו`);
        }

        let successCount = 0;
        let errorCount = 0;

        for (const row of valid) {
            try {
                const parsedStartDate = (row as any)._startDateParsed as string | undefined;
                await addPhone({
                    phone: row.phone || '000-0000000',
                    domain: row.domain || '',
                    website: row.website || '',
                    owner: row.owner,
                    email: row.email,
                    package: row.package,
                    amount: Number(row.amount),
                    status: row.status as any,
                    priority: row.priority as any,
                    nextPayment: row.nextPayment,
                    startDate: parsedStartDate || new Date().toISOString().slice(0, 10),
                    notes: row.notes || '',
                    lastUpdate: new Date().toISOString().split('T')[0],
                    createdAt: (row as any)._createdAtParsed || new Date().toISOString(),
                    updatedAt: new Date().toISOString(),
                });
                successCount++;
            } catch (error) {
                console.error('Error importing phone:', error);
                errorCount++;
            }
        }

        setIsProcessing(false);
        setShowPreview(false);
        setPreviewData([]);

        if (successCount > 0) {
            toast.success(`${successCount} דומיינים יובאו בהצלחה!`);
            addNotification({
                type: 'success',
                title: 'ייבוא CSV',
                message: `${successCount} דומיינים יובאו בהצלחה מ-CSV`,
                duration: 5000,
                timestamp: new Date(),
            });
        }

        if (errorCount > 0) {
            toast.error(`${errorCount} דומיינים נכשלו בייבוא`);
        }

        // Close modal immediately after import
        onClose();
    };

    const downloadTemplate = () => {
        const template = 'phone,domain,website,owner,email,package,amount,status,priority,nextPayment,notes\n050-1234567,example.co.il,https://example.co.il,חברת אורל,info@example.co.il,Linux Mini,299.99,renewal,medium,2025-12-31,הערה לדוגמה';
        const blob = new Blob([template], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'phones_template.csv';
        link.click();
    };

    // 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-4xl w-full mx-4 max-h-[90vh] overflow-hidden"
                onClick={(e) => e.stopPropagation()}
            >
                <div className="flex items-center justify-between p-6 border-b border-gray-200">
                    <div className="flex items-center">
                        <Upload 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 overflow-y-auto max-h-[calc(90vh-140px)]">
                    {!showPreview ? (
                        <div className="space-y-6">
                            <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">
                                    בחר קובץ CSV לייבוא
                                </h3>
                                <p className="text-sm text-gray-500 mb-4">
                                    הקובץ צריך לכלול את העמודות: phone, domain, website, owner, email, package, amount, status, priority, nextPayment, notes
                                </p>
                                <p className="text-xs text-gray-500">
                                    ערכי סטטוס מותרים: paid, pending, overdue, free, paused, delete_backup, delete_no_backup, renewal
                                </p>
                            </div>

                            <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center">
                                <input
                                    ref={fileInputRef}
                                    type="file"
                                    accept=".csv,.tsv,.txt,.xlsx"
                                    onChange={handleFileSelect}
                                    className="hidden"
                                    title="בחר קובץ CSV/TSV"
                                    aria-label="בחר קובץ CSV או TSV לייבוא"
                                />
                                <button
                                    onClick={() => fileInputRef.current?.click()}
                                    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"
                                >
                                    <Upload className="w-4 h-4 ml-2" />
                                    בחר קובץ CSV
                                </button>
                            </div>

                            <div className="text-center">
                                <button
                                    onClick={downloadTemplate}
                                    className="text-sm text-blue-600 hover:text-blue-800 underline"
                                >
                                    הורד תבנית CSV לדוגמה
                                </button>
                            </div>
                        </div>
                    ) : (
                        <div className="space-y-4">
                            <div className="flex items-center justify-between">
                                <h3 className="text-lg font-medium text-gray-900">
                                    תצוגה מקדימה - {previewData.length} דומיינים
                                </h3>
                                <button
                                    onClick={() => setShowPreview(false)}
                                    className="text-sm text-gray-500 hover:text-gray-700"
                                >
                                    בחר קובץ אחר
                                </button>
                            </div>

                            <div className="overflow-x-auto">
                                <table className="min-w-full divide-y divide-gray-200">
                                    <thead className="bg-gray-50">
                                        <tr>
                                            <th className="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase">פלאפון</th>
                                            <th className="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase">דומיין</th>
                                            <th className="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase">בעלים</th>
                                            <th className="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase">אימייל</th>
                                            <th className="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase">סכום</th>
                                            <th className="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase">סטטוס</th>
                                        </tr>
                                    </thead>
                                    <tbody className="bg-white divide-y divide-gray-200">
                                        {previewData.slice(0, 10).map((row, index) => {
                                            const amountNum = Number(row.amount);
                                            const isValid =
                                                row.phone &&
                                                row.domain &&
                                                row.owner &&
                                                row.email &&
                                                !Number.isNaN(amountNum);

                                            return (
                                                <tr key={index}>
                                                    <td className="px-3 py-2 text-sm text-gray-900">{row.phone}</td>
                                                    <td className="px-3 py-2 text-sm text-gray-900">{row.domain}</td>
                                                    <td className="px-3 py-2 text-sm text-gray-900">{row.owner}</td>
                                                    <td className="px-3 py-2 text-sm text-gray-900">{row.email}</td>
                                                    <td className="px-3 py-2 text-sm text-gray-900">₪{row.amount}</td>
                                                    <td className="px-3 py-2 text-sm">
                                                        <div className="flex items-center">
                                                            {isValid ? (
                                                                <CheckCircle className="w-4 h-4 text-green-500 ml-2" />
                                                            ) : (
                                                                <AlertCircle className="w-4 h-4 text-red-500 ml-2" />
                                                            )}
                                                            <span className={isValid ? 'text-green-700' : 'text-red-700'}>
                                                                {isValid ? 'תקין' : 'לא תקין'}
                                                            </span>
                                                        </div>
                                                    </td>
                                                </tr>
                                            );
                                        })}
                                    </tbody>
                                </table>
                                {previewData.length > 10 && (
                                    <p className="text-sm text-gray-500 mt-2 text-center">
                                        מציג 10 מתוך {previewData.length} דומיינים
                                    </p>
                                )}
                            </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>
                    {showPreview && (
                        <button
                            onClick={handleImport}
                            disabled={isProcessing}
                            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"
                        >
                            {isProcessing ? 'מייבא...' : 'ייבוא דומיינים'}
                        </button>
                    )}
                </div>
            </div>
        </div>
    );
}
