import React, { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';

import { Button } from 'primereact/button';
import { Card } from 'primereact/card';
import { Dropdown } from 'primereact/dropdown';
import { Message } from 'primereact/message';
import { Skeleton } from 'primereact/skeleton';

import { schemaPickerService } from '../service/rendicontazioneService';

/**
 * SchemaTemplatePicker
 * Mostrato quando un bando non ha ancora uno schema di rendicontazione.
 * Offre 3 modalita: schema nuovo vuoto, da template predefinito, clone da altro bando.
 *
 * Props:
 *   callId         number — bando target
 *   onInitialized  fn(schemaData) — chiamato dopo initialize con successo
 *   onError        fn(err)
 */
const SchemaTemplatePicker = ({ callId, onInitialized, onError }) => {
    const [templates, setTemplates] = useState([]);
    const [clonableCalls, setClonableCalls] = useState([]);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);

    // Selezione utente
    const [mode, setMode] = useState(null);            // null | 'blank' | 'template' | 'clone'
    const [pickedTemplateId, setPickedTemplateId] = useState(null);
    const [pickedSourceCallId, setPickedSourceCallId] = useState(null);

    useEffect(() => {
        let active = true;
        setLoading(true);
        let tpls = null, clones = null;
        const finish = () => {
            if (tpls !== null && clones !== null && active) setLoading(false);
        };

        schemaPickerService.listTemplates(
            (resp) => { if (active) { tpls = resp?.data?.templates || []; setTemplates(tpls); } finish(); },
            (err) => { tpls = []; finish(); if (onError) onError(err); }
        );
        schemaPickerService.listClonableCalls(
            (resp) => { if (active) { clones = resp?.data?.calls || []; setClonableCalls(clones); } finish(); },
            (err) => { clones = []; finish(); }
        );
        return () => { active = false; };
    }, []);  // eslint-disable-line react-hooks/exhaustive-deps

    const canSubmit = () => {
        if (!mode) return false;
        if (mode === 'blank') return true;
        if (mode === 'template') return !!pickedTemplateId;
        if (mode === 'clone') return !!pickedSourceCallId;
        return false;
    };

    const handleSubmit = () => {
        const payload = { source: mode };
        if (mode === 'template') payload.template_id = pickedTemplateId;
        if (mode === 'clone') payload.source_call_id = pickedSourceCallId;

        setSaving(true);
        schemaPickerService.initializeSchema(callId, payload,
            (resp) => { setSaving(false); if (onInitialized) onInitialized(resp?.data); },
            (err) => { setSaving(false); if (onError) onError(err); }
        );
    };

    if (loading) {
        return (
            <div className="grid">
                <div className="col-12 md:col-4"><Skeleton height="14rem"/></div>
                <div className="col-12 md:col-4"><Skeleton height="14rem"/></div>
                <div className="col-12 md:col-4"><Skeleton height="14rem"/></div>
            </div>
        );
    }

    const templateOptions = templates
        .filter(t => t.template_id !== 'blank')  // blank ha card dedicata
        .map(t => ({ label: t.label, value: t.template_id, description: t.description }));

    const cloneOptions = clonableCalls.map(c => ({
        label: `${c.name} · ${c.schema_status === 'PUBLISHED' ? __('Pubblicato','gepafin') : __('Bozza','gepafin')}`,
        value: c.call_id,
    }));

    const cardStyle = (selected) => ({
        cursor: 'pointer',
        height: '100%',
        border: selected ? '2px solid var(--primary-color)' : '2px solid transparent',
        transition: 'border-color 0.15s'
    });

    return (
        <div>
            <div style={{ marginBottom: '1rem' }}>
                <h3>{__('Scegli come iniziare lo schema di rendicontazione','gepafin')}</h3>
                <p className="text-color-secondary" style={{ marginTop: 0 }}>
                    {__("Puoi partire da un modello vuoto, usare un template predefinito oppure clonare lo schema di un altro bando. Lo schema creato sarà in bozza e modificabile liberamente.", 'gepafin')}
                </p>
            </div>

            <div className="grid">
                {/* Card 1: NUOVO SCHEMA VUOTO */}
                <div className="col-12 md:col-4">
                    <Card
                        title={<><i className="pi pi-plus-circle" style={{ marginRight: '0.5rem', color: 'var(--primary-color)' }} />{__('Nuovo schema','gepafin')}</>}
                        style={cardStyle(mode === 'blank')}
                        onClick={() => setMode('blank')}
                    >
                        <p style={{ fontSize: '0.9em' }}>
                            {__('Parti da zero con sezioni vuote. Configurerai categorie di spesa, documenti richiesti e controlli aggiuntivi secondo le esigenze del bando.','gepafin')}
                        </p>
                        <div style={{ fontSize: '0.85em', color: 'var(--text-color-secondary)' }}>
                            {__('Consigliato se il bando è nuovo e non somiglia a bandi precedenti.','gepafin')}
                        </div>
                    </Card>
                </div>

                {/* Card 2: DA TEMPLATE */}
                <div className="col-12 md:col-4">
                    <Card
                        title={<><i className="pi pi-book" style={{ marginRight: '0.5rem', color: 'var(--primary-color)' }} />{__('Da template','gepafin')}</>}
                        style={cardStyle(mode === 'template')}
                        onClick={() => setMode('template')}
                    >
                        <p style={{ fontSize: '0.9em' }}>
                            {__('Parti da un template predefinito che replica schemi di bandi noti (es. RE-START). Potrai comunque modificare tutto.','gepafin')}
                        </p>
                        {mode === 'template' && (
                            <div style={{ marginTop: '0.5rem' }} onClick={(e) => e.stopPropagation()}>
                                <Dropdown
                                    value={pickedTemplateId}
                                    onChange={(e) => setPickedTemplateId(e.value)}
                                    options={templateOptions}
                                    placeholder={__('Scegli un template...','gepafin')}
                                    style={{ width: '100%' }}
                                />
                                {pickedTemplateId && (
                                    <small className="text-color-secondary" style={{ display: 'block', marginTop: '0.4rem' }}>
                                        {templateOptions.find(t => t.value === pickedTemplateId)?.description}
                                    </small>
                                )}
                            </div>
                        )}
                    </Card>
                </div>

                {/* Card 3: CLONE */}
                <div className="col-12 md:col-4">
                    <Card
                        title={<><i className="pi pi-copy" style={{ marginRight: '0.5rem', color: 'var(--primary-color)' }} />{__('Clona da bando','gepafin')}</>}
                        style={cardStyle(mode === 'clone')}
                        onClick={() => setMode('clone')}
                    >
                        <p style={{ fontSize: '0.9em' }}>
                            {__('Copia lo schema di un altro bando (in bozza o pubblicato). Utile se il nuovo bando è molto simile a uno esistente.','gepafin')}
                        </p>
                        {mode === 'clone' && (
                            <div style={{ marginTop: '0.5rem' }} onClick={(e) => e.stopPropagation()}>
                                {cloneOptions.length === 0 ? (
                                    <Message severity="warn"
                                        text={__('Nessun bando con schema configurato da cui clonare.','gepafin')}
                                        style={{ width: '100%' }} />
                                ) : (
                                    <Dropdown
                                        value={pickedSourceCallId}
                                        onChange={(e) => setPickedSourceCallId(e.value)}
                                        options={cloneOptions}
                                        placeholder={__('Scegli un bando sorgente...','gepafin')}
                                        style={{ width: '100%' }}
                                    />
                                )}
                            </div>
                        )}
                    </Card>
                </div>
            </div>

            <div style={{ marginTop: '1.5rem', display: 'flex', justifyContent: 'flex-end', gap: '0.5rem' }}>
                <Button
                    label={__('Inizia','gepafin')}
                    icon="pi pi-arrow-right"
                    iconPos="right"
                    disabled={!canSubmit() || saving}
                    loading={saving}
                    onClick={handleSubmit}
                />
            </div>
        </div>
    );
};

export default SchemaTemplatePicker;
