'use client';

import React, { useState } from 'react';
import { Button, Collapse, List, Space, Tag, Typography } from 'antd';
import { Sparkles } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import ContentCard from '@/components/layouts/ContentCard';
import { useTarefaResumoIa } from '../hooks/useTarefaResumoIa';

const { Paragraph, Text } = Typography;

export type TarefaResumoIaCardProps = {
    tarefaId: number;
    disabled?: boolean;
    /** Quando true, envolve o conteúdo num Collapse fechado por padrão. */
    collapsible?: boolean;
    onResumoGenerated?: () => void;
};

export function TarefaResumoIaCard({
    tarefaId,
    disabled,
    collapsible = false,
    onResumoGenerated,
}: TarefaResumoIaCardProps) {
    const resumoMutation = useTarefaResumoIa();
    const [resumo, setResumo] = useState<string | null>(null);
    const [sugestoes, setSugestoes] = useState<string[]>([]);
    const [fonte, setFonte] = useState<'ia' | 'regra' | null>(null);
    const [collapseOpen, setCollapseOpen] = useState<string[]>([]);

    const gerar = async () => {
        const payload = await resumoMutation.mutateAsync(tarefaId);
        setResumo(payload.resumo);
        setSugestoes(payload.sugestoes ?? []);
        setFonte(payload.fonte);
        setCollapseOpen(['ia']);
        onResumoGenerated?.();
    };

    const generateButton = (
        <Button
            type="default"
            size="small"
            icon={<Sparkles size={14} aria-hidden />}
            loading={resumoMutation.isPending}
            disabled={disabled || resumoMutation.isPending}
            onClick={() => void gerar()}
            data-testid="tarefa-gerar-resumo-ia"
        >
            {resumo ? 'Atualizar' : 'Gerar resumo'}
        </Button>
    );

    const summaryBody = resumo ? (
        <>
            <Paragraph style={{ marginBottom: sugestoes.length > 0 ? 12 : 0 }}>{resumo}</Paragraph>
            {sugestoes.length > 0 ? (
                <>
                    <Text type="secondary">Próximos passos sugeridos</Text>
                    <List
                        size="small"
                        dataSource={sugestoes}
                        renderItem={(item) => <List.Item>{item}</List.Item>}
                    />
                </>
            ) : null}
        </>
    ) : (
        <Text type="secondary">
            Gere um resumo do estado da tarefa, riscos de prazo e sugestões de acção (IA ou regras quando a
            IA não estiver disponível).
        </Text>
    );

    if (collapsible) {
        return (
            <Collapse
                activeKey={collapseOpen}
                onChange={(keys) => setCollapseOpen(Array.isArray(keys) ? keys : [keys])}
                items={[
                    {
                        key: 'ia',
                        label: (
                            <Space>
                                <Sparkles size={ICON_SIZE_MD} aria-hidden />
                                <span>Resumo assistido</span>
                                {fonte ? (
                                    <Tag color={fonte === 'ia' ? 'processing' : 'default'}>
                                        {fonte === 'ia' ? 'IA' : 'Regras'}
                                    </Tag>
                                ) : null}
                            </Space>
                        ),
                        children: (
                            <>
                                <div style={{ marginBottom: 12, display: 'flex', justifyContent: 'flex-end' }}>
                                    {generateButton}
                                </div>
                                {summaryBody}
                            </>
                        ),
                    },
                ]}
            />
        );
    }

    return (
        <ContentCard
            title={
                <Space>
                    <Sparkles size={ICON_SIZE_MD} aria-hidden />
                    <span>Resumo assistido</span>
                    {fonte ? (
                        <Tag color={fonte === 'ia' ? 'processing' : 'default'}>
                            {fonte === 'ia' ? 'IA' : 'Regras'}
                        </Tag>
                    ) : null}
                </Space>
            }
            extra={generateButton}
        >
            {summaryBody}
        </ContentCard>
    );
}
