'use client';

/**
 * SLA / SLO tipológico — `/projetos/[id]/software/sla`
 */

import { Plus, Save } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import React, { useEffect, useMemo, useState } from 'react';
import { useParams } from 'next/navigation';
import { Button, Col, Form, Input, InputNumber, Modal, Row, Select, Space, Switch, Tabs, Tooltip } from 'antd';
import { message } from '@/lib/feedback/message';
import { notifyApiError } from '@/lib/feedback/notifyApiError';
import { confirmDialog } from '@/lib/feedback/confirmDialog';
import { FormTextarea } from '@/components/form';
import {
    useWaygestFormModalProps,
    waygestFormModalFooterClassName,
} from '@/hooks/useWaygestFormModalProps';
import { useQueryCache } from '@/hooks/useQueryCache';
import { useMutationCache } from '@/hooks/useMutationCache';
import { useProjetoWriteGates } from '@/features/projetos/hooks/useProjetoWriteGates';
import { queryKeys } from '@/lib/cache/queryKeys';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import apiClient from '@/lib/api/client';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import { ListPageCreateFloatButton } from '@/components/listings';
import { LazyDataTable } from '@/components/lazy';
import {
    ProjetoTipologicoEmptyState,
} from '@/features/projetos/projeto-tipologico-empty-state';
import type { ProjetoSoftwareSlaPerfil, ProjetoSoftwareSlaSeveridade } from './types';

const FORM_SLA = 'projeto-sla-perfil-form';
const FORM_SEV = 'projeto-sla-severidade-form';

const CRIT = [
    { label: 'Baixa', value: 'baixa' },
    { label: 'Média', value: 'media' },
    { label: 'Alta', value: 'alta' },
    { label: 'Crítica', value: 'critica' },
];

const SEV = [
    { label: 'Crítica', value: 'critica' },
    { label: 'Alta', value: 'alta' },
    { label: 'Média', value: 'media' },
    { label: 'Baixa', value: 'baixa' },
];

export function ProjetoSoftwareSlaScreen() {
    const params = useParams();
    const id = params?.id as string;
    const { canEditar, tooltipSemPermissao } = useProjetoWriteGates();
    const tooltipSemEdicao = !canEditar ? tooltipSemPermissao('editar SLA') : undefined;

    const [sevModal, setSevModal] = useState(false);
    const [editingSev, setEditingSev] = useState<ProjetoSoftwareSlaSeveridade | null>(null);
    const [slaForm] = Form.useForm();
    const [sevForm] = Form.useForm();
    const formModalLayout = useWaygestFormModalProps();

    const {
        data: slaData,
        isLoading: loadingSla,
        refetch: refetchSla,
    } = useQueryCache<ProjetoSoftwareSlaPerfil>({
        queryKey: queryKeys.projetos.slaPerfil(id),
        endpoint: API_ENDPOINTS.projetos.slaPerfil.show(id),
        enabled: !!id,
        staleTime: 60_000,
    });

    const {
        data: sevData,
        isLoading: loadingSev,
        refetch: refetchSev,
    } = useQueryCache<{ data: ProjetoSoftwareSlaSeveridade[] } | ProjetoSoftwareSlaSeveridade[]>({
        queryKey: queryKeys.projetos.slaSeveridades(id),
        endpoint: API_ENDPOINTS.projetos.slaSeveridades.index(id),
        enabled: !!id,
        staleTime: 60_000,
    });

    const severidades = useMemo(() => {
        if (Array.isArray(sevData)) return sevData;
        return sevData?.data ?? [];
    }, [sevData]);

    useEffect(() => {
        if (!slaData) return;
        slaForm.setFieldsValue({
            ...slaData,
            confirmado_manual: !!slaData.confirmado_manual,
        });
    }, [slaData, slaForm]);

    const saveSla = useMutationCache({
        mutationFn: async (values: Record<string, unknown>) => {
            await apiClient.put(API_ENDPOINTS.projetos.slaPerfil.update(id), {
                ...values,
                origem: 'manual',
                confianca: values.confirmado_manual ? 'alta' : 'media',
            });
        },
        onSuccess: async () => {
            message.success('Perfil SLA/SLO salvo.');
            await refetchSla();
        },
        onError: (e) => notifyApiError(e, 'Não foi possível salvar o SLA.'),
    });

    const saveSev = useMutationCache({
        mutationFn: async (values: Record<string, unknown>) => {
            if (editingSev) {
                await apiClient.put(
                    API_ENDPOINTS.projetos.slaSeveridades.update(id, editingSev.id),
                    values
                );
            } else {
                await apiClient.post(API_ENDPOINTS.projetos.slaSeveridades.store(id), values);
            }
        },
        onSuccess: async () => {
            message.success(editingSev ? 'Severidade atualizada.' : 'Severidade criada.');
            setSevModal(false);
            setEditingSev(null);
            sevForm.resetFields();
            await Promise.all([refetchSev(), refetchSla()]);
        },
        onError: (e) => notifyApiError(e, 'Não foi possível salvar a severidade.'),
    });

    const deleteSev = async (row: ProjetoSoftwareSlaSeveridade) => {
        await confirmDialog({
            title: 'Excluir severidade?',
            content: `Remover nível “${row.severidade}”?`,
            okText: 'Excluir',
            okType: 'danger',
            onOk: async () => {
                try {
                    await apiClient.delete(API_ENDPOINTS.projetos.slaSeveridades.destroy(id, row.id));
                    message.success('Severidade excluída.');
                    await refetchSev();
                } catch (e) {
                    notifyApiError(e, 'Não foi possível excluir.');
                }
            },
        });
    };

    const openSev = (row?: ProjetoSoftwareSlaSeveridade) => {
        setEditingSev(row ?? null);
        if (row) {
            sevForm.setFieldsValue(row);
        } else {
            sevForm.resetFields();
            sevForm.setFieldsValue({ ordem: 0 });
        }
        setSevModal(true);
    };

    return (
        <ProjetoLayout
            projetoId={id}
            pageTitle="SLA / SLO"
            pageIcon="handshake"
            titleSection="Segurança"
            breadcrumbItems={[
                { title: 'PROJETO' },
                { title: 'Projeto', path: `/projetos/${id}` },
                { title: 'SLA / SLO' },
            ]}
            data-testid="projeto-sla"
        >
            
            <Tabs
                items={[
                    {
                        key: 'perfil',
                        label: 'Perfil',
                        children: (
                            <Form
                                id={FORM_SLA}
                                form={slaForm}
                                layout="vertical"
                                disabled={!canEditar}
                                onFinish={(v) => saveSla.mutate(v)}
                            >
                                <Row gutter={16}>
                                    <Col xs={24} md={8}>
                                        <Form.Item name="criticidade_projeto" label="Criticidade do projeto">
                                            <Select allowClear options={CRIT} />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} md={8}>
                                        <Form.Item name="disponibilidade_alvo" label="Disponibilidade alvo">
                                            <Input placeholder="Ex.: 99,5%" />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} md={8}>
                                        <Form.Item name="tempo_resposta_alvo" label="Tempo de resposta alvo">
                                            <Input placeholder="Ex.: p95 < 400ms" />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} md={8}>
                                        <Form.Item name="rto" label="RTO">
                                            <Input />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} md={8}>
                                        <Form.Item name="rpo" label="RPO">
                                            <Input />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} md={8}>
                                        <Form.Item
                                            name="usuarios_simultaneos_esperados"
                                            label="Usuários simultâneos esperados"
                                        >
                                            <InputNumber min={0} style={{ width: '100%' }} />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} md={12}>
                                        <Form.Item name="horario_suporte" label="Horário de suporte">
                                            <Input placeholder="Ex.: 8h–18h (dias úteis)" />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} md={12}>
                                        <Form.Item name="janela_manutencao" label="Janela de manutenção">
                                            <Input />
                                        </Form.Item>
                                    </Col>
                                    <Col span={24}>
                                        <Form.Item name="sla_texto" label="SLA">
                                            <FormTextarea rows={3} />
                                        </Form.Item>
                                    </Col>
                                    <Col span={24}>
                                        <Form.Item name="slo_texto" label="SLO">
                                            <FormTextarea rows={3} />
                                        </Form.Item>
                                    </Col>
                                    <Col span={24}>
                                        <Form.Item name="escalonamento" label="Escalonamento">
                                            <FormTextarea rows={2} />
                                        </Form.Item>
                                    </Col>
                                    <Col span={24}>
                                        <Form.Item name="observacoes" label="Observações">
                                            <FormTextarea rows={2} />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} md={8}>
                                        <Form.Item
                                            name="confirmado_manual"
                                            label="Confirmado manualmente"
                                            valuePropName="checked"
                                        >
                                            <Switch />
                                        </Form.Item>
                                    </Col>
                                </Row>
                                <Tooltip title={tooltipSemEdicao}>
                                    <Button
                                        type="primary"
                                        htmlType="submit"
                                        icon={<Save size={ICON_SIZE_MD} />}
                                        loading={saveSla.isPending || loadingSla}
                                        disabled={!canEditar}
                                    >
                                        Salvar perfil
                                    </Button>
                                </Tooltip>
                            </Form>
                        ),
                    },
                    {
                        key: 'severidades',
                        label: 'Severidades',
                        children: (
                            <>
                                {severidades.length === 0 && !loadingSev ? (
                                    <ProjetoTipologicoEmptyState
                                        title="Nenhuma severidade SLA"
                                        domainKey="sla"
                                        projetoId={id}
                                        primaryAction={
                                            canEditar ? (
                                                <Button type="primary" onClick={() => openSev()}>
                                                    Adicionar severidade
                                                </Button>
                                            ) : undefined
                                        }
                                    />
                                ) : (
                                    <LazyDataTable
                                        rowKey="id"
                                        loading={loadingSev}
                                        data={severidades}
                                        pagination={false}
                                        columns={[
                                            { title: 'Severidade', dataIndex: 'severidade' },
                                            { title: 'Atendimento', dataIndex: 'tempo_atendimento' },
                                            { title: 'Resolução', dataIndex: 'tempo_resolucao' },
                                            {
                                                title: 'Ações',
                                                key: 'acoes',
                                                render: (_: unknown, row: ProjetoSoftwareSlaSeveridade) => (
                                                    <Space>
                                                        <Button
                                                            size="small"
                                                            disabled={!canEditar}
                                                            onClick={() => openSev(row)}
                                                        >
                                                            Editar
                                                        </Button>
                                                        <Button
                                                            size="small"
                                                            danger
                                                            disabled={!canEditar}
                                                            onClick={() => deleteSev(row)}
                                                        >
                                                            Excluir
                                                        </Button>
                                                    </Space>
                                                ),
                                            },
                                        ]}
                                        ariaRegionLabel="SLAs do projeto"
                                        autoMobileFromColumns={{
                                            testIdPrefix: 'software-sla-severidades',
                                            listHeading: 'Severidades de SLA',
                                            getFallbackTitle: (r) =>
                                                r.severidade?.trim() || `SLA ${r.id}`,
                                        }}
                                    />
                                )}
                                {canEditar ? (
                                    <ListPageCreateFloatButton
                                        icon={<Plus size={ICON_SIZE_MD} aria-hidden />}
                                        onClick={() => openSev()}
                                        aria-label="Adicionar severidade SLA"
                                    />
                                ) : null}
                            </>
                        ),
                    },
                ]}
            />
            

            <Modal
                {...formModalLayout}
                title={editingSev ? 'Editar severidade' : 'Nova severidade'}
                open={sevModal}
                onCancel={() => {
                    setSevModal(false);
                    setEditingSev(null);
                }}
                footer={
                    <div className={waygestFormModalFooterClassName}>
                        <Button onClick={() => setSevModal(false)}>Cancelar</Button>
                        <Button
                            type="primary"
                            form={FORM_SEV}
                            htmlType="submit"
                            loading={saveSev.isPending}
                            disabled={!canEditar}
                        >
                            Salvar
                        </Button>
                    </div>
                }
            >
                <Form id={FORM_SEV} form={sevForm} layout="vertical" onFinish={(v) => saveSev.mutate(v)} scrollToFirstError>
                    <Form.Item name="severidade" label="Severidade" rules={[{ required: true }]}>
                        <Select options={SEV} />
                    </Form.Item>
                    <Form.Item name="tempo_atendimento" label="Tempo de atendimento">
                        <Input placeholder="Ex.: 1h" />
                    </Form.Item>
                    <Form.Item name="tempo_resolucao" label="Tempo de resolução">
                        <Input placeholder="Ex.: 8h" />
                    </Form.Item>
                    <Form.Item name="ordem" label="Ordem">
                        <InputNumber min={0} style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item name="observacoes" label="Observações">
                        <FormTextarea rows={2} />
                    </Form.Item>
                </Form>
            </Modal>
        </ProjetoLayout>
    );
}
