import { useState, useEffect } from 'react';
import { router } from '@inertiajs/react';
import Modal from '../Modal/Modal';
import Button from '../Button/Button';
import { PartnerShow } from '@/types';

interface PartnerLineupEditorModalProps {
    isOpen: boolean;
    onClose: () => void;
    show: PartnerShow | null;
    type: 'lineup' | 'seitansai' | 'graduation';
}

export default function PartnerLineupEditorModal({ isOpen, onClose, show, type }: PartnerLineupEditorModalProps) {
    const [jsonData, setJsonData] = useState('');
    const [isProcessing, setIsProcessing] = useState(false);
    const [jsonError, setJsonError] = useState<string | null>(null);

    // Initialize dengan data yang sudah ada
    useEffect(() => {
        if (show && isOpen) {
            const currentData = show[type];
            if (currentData && Array.isArray(currentData) && currentData.length > 0) {
                setJsonData(JSON.stringify(currentData, null, 2));
            } else {
                setJsonData('[]');
            }
            setJsonError(null);
        }
    }, [show, type, isOpen]);

    const handleSave = () => {
        if (!show) {
            return;
        }

        // Validate JSON
        try {
            const parsed = JSON.parse(jsonData);
            if (!Array.isArray(parsed)) {
                setJsonError('Data harus berupa array');
                return;
            }

            // Validate each item has required fields
            for (const item of parsed) {
                if (typeof item !== 'object' || item === null) {
                    setJsonError('Setiap item harus berupa object');
                    return;
                }
            }

            setJsonError(null);
            setIsProcessing(true);

            // Update show dengan data baru - kirim semua field yang diperlukan
            const updateData: any = {
                [type]: parsed,
                showId: show.showId,
                title: show.title,
                description: show.description || '',
                start_time: show.start_time,
                type: show.type,
                price: show.price,
                banner_link: show.banner_link || '',
                is_promo: show.is_promo ? 1 : 0,
                promo_price: show.promo_price || '',
                is_active: show.is_active ? 1 : 0,
                is_live: show.is_live ? 1 : 0,
                is_replay: show.is_replay ? 1 : 0,
                streamer_live: show.streamer_live,
                slug_live: show.slug_live,
                url_live: show.url_live || '',
                url_replay: show.url_replay || '',
                type_live: show.type_live,
            };

            // Preserve other lineup fields
            if (type !== 'lineup') {
                updateData.lineup = show.lineup || [];
            }
            if (type !== 'seitansai') {
                updateData.seitansai = show.seitansai || [];
            }
            if (type !== 'graduation') {
                updateData.graduation = show.graduation || [];
            }

            router.put(
                `/partner/shows/${show.id}`,
                updateData,
                {
                    preserveState: true,
                    preserveScroll: true,
                    onSuccess: () => {
                        setIsProcessing(false);
                        onClose();
                    },
                    onError: () => {
                        setIsProcessing(false);
                    },
                }
            );
        } catch (error) {
            setJsonError('Format JSON tidak valid');
        }
    };

    const handleFormat = () => {
        try {
            const parsed = JSON.parse(jsonData);
            setJsonData(JSON.stringify(parsed, null, 2));
            setJsonError(null);
        } catch (error) {
            setJsonError('Format JSON tidak valid');
        }
    };

    const getTypeLabel = () => {
        switch (type) {
            case 'lineup':
                return 'Lineup';
            case 'seitansai':
                return 'Seitansai';
            case 'graduation':
                return 'Graduation';
            default:
                return 'Data';
        }
    };

    if (!show) {
        return null;
    }

    return (
        <Modal
            isOpen={isOpen}
            onClose={onClose}
            title={`Edit ${getTypeLabel()} - ${show.title}`}
            size="lg"
            footer={
                <div className="flex items-center justify-between">
                    <Button variant="secondary" onClick={handleFormat} disabled={isProcessing}>
                        <i className="fas fa-code mr-2"></i>
                        Format JSON
                    </Button>
                    <div className="flex gap-2">
                        <Button variant="secondary" onClick={onClose} disabled={isProcessing}>
                            Batal
                        </Button>
                        <Button onClick={handleSave} disabled={isProcessing || !!jsonError}>
                            {isProcessing ? 'Menyimpan...' : 'Simpan'}
                        </Button>
                    </div>
                </div>
            }
        >
            <div className="space-y-4">
                <div>
                    <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                        Data {getTypeLabel()} (JSON Array)
                    </label>
                    <textarea
                        value={jsonData}
                        onChange={(e) => {
                            setJsonData(e.target.value);
                            setJsonError(null);
                        }}
                        rows={15}
                        className={`block w-full rounded-md border-gray-300 shadow-sm focus:border-[#d4af37] focus:ring-[#d4af37] dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:focus:border-[#b8941f] dark:focus:ring-[#b8941f] font-mono text-sm ${
                            jsonError ? 'border-red-300 dark:border-red-600' : ''
                        }`}
                        placeholder='[{"id":"277","name":"Aralie","img":"https://...","url_key":"aralie"}]'
                    />
                    {jsonError && (
                        <p className="mt-2 text-sm text-red-600 dark:text-red-400">
                            <i className="fas fa-exclamation-circle mr-1"></i>
                            {jsonError}
                        </p>
                    )}
                    <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">
                        Format: Array of objects dengan fields: id, name, img, url_key
                    </p>
                </div>

                {/* Example */}
                <div className="rounded-lg border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-800">
                    <p className="text-xs font-semibold text-gray-700 dark:text-gray-300 mb-1">
                        Contoh Format:
                    </p>
                    <pre className="text-xs text-gray-600 dark:text-gray-400 overflow-x-auto">
                        {`[
  {
    "id": "277",
    "name": "Aralie",
    "img": "https://...",
    "url_key": "aralie"
  }
]`}
                    </pre>
                </div>
            </div>
        </Modal>
    );
}

