'use client';

import React, { useState } from 'react';
import { Form, Input, Button, Space, Card } from 'antd';
import { message } from '@/lib/feedback/message';
import { Send } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import { FileUpload } from '@/components/upload';
import apiClient from '@/lib/api/client';
import type { UploadFile } from 'antd/es/upload';
import styles from './CommentForm.module.scss';

const { TextArea } = Input;

interface CommentFormProps {
    projetoId: number;
    endpoint: string;
    onSuccess?: () => void;
    placeholder?: string;
    showAttachments?: boolean;
    /** Sem Card exterior — o contentor fica a cargo do pai (ex.: feed de atividade). */
    embedded?: boolean;
}

export function CommentForm({
    projetoId: _projetoId,
    endpoint,
    onSuccess,
    placeholder = 'Digite seu comentário...',
    showAttachments = true,
    embedded = false,
}: CommentFormProps) {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [files, setFiles] = useState<UploadFile[]>([]);

    const handleSubmit = async (values: Record<string, unknown>) => {
        try {
            setLoading(true);
            const formData = new FormData();
            formData.append('conteudo', String(values.conteudo));
            formData.append('tipo', 'comentario');

            // Adicionar arquivos
            files.forEach((file) => {
                if (file.originFileObj) {
                    formData.append('anexos[]', file.originFileObj);
                }
            });

            await apiClient.post(endpoint, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });

            message.success('Comentário adicionado com sucesso!');
            form.resetFields();
            setFiles([]);
            onSuccess?.();
        } catch (error: unknown) {
            const errorMessage =
                (error as { response?: { data?: { message?: string } } })?.response?.data
                    ?.message || 'Erro ao adicionar comentário';
            message.error(errorMessage);
        } finally {
            setLoading(false);
        }
    };

    const submitButton = (
        <Button
            type="primary"
            htmlType="submit"
            loading={loading}
            icon={<Send size={ICON_SIZE_MD} aria-hidden />}
            className={embedded ? styles.embeddedSubmit : undefined}
            block={embedded}
        >
            Enviar comentário
        </Button>
    );

    const formContent = (
        <Form
            form={form}
            onFinish={handleSubmit}
            layout="vertical"
            className={embedded ? styles.embeddedForm : undefined}
        >
            <Form.Item
                name="conteudo"
                className={embedded ? styles.textareaItem : undefined}
                rules={[{ required: true, message: 'Digite um comentário' }]}
            >
                <TextArea
                    rows={embedded ? 3 : 4}
                    placeholder={placeholder}
                    maxLength={2000}
                    showCount
                />
            </Form.Item>

            {showAttachments && (
                <Form.Item label="Anexos">
                    <FileUpload
                        value={files}
                        onChange={setFiles}
                        maxCount={5}
                        maxSize={10}
                        listType="text"
                    />
                </Form.Item>
            )}

            <Form.Item className={embedded ? styles.actionsItem : undefined}>
                {embedded ? submitButton : <Space>{submitButton}</Space>}
            </Form.Item>
        </Form>
    );

    if (embedded) {
        return formContent;
    }

    return (
        <Card size="small" style={{ marginBottom: 16 }}>
            {formContent}
        </Card>
    );
}
