'use client';

import { useCallback, useEffect, useState } from 'react';
import Swal from 'sweetalert2';
import { RequireRole, useAuth } from '@/lib/auth-context';
import {
  createProcedure,
  listProcedures,
  Procedure,
  removeProcedure,
  updateProcedure,
} from '@/lib/services/treatments';
import { EmptyState, ErrorAlert, Loading, Modal, PageHeader } from '@/components/app/ui';
import { extractApiError } from '@/lib/api-client';
import { centsToInput, formatCents, parseMoneyToCents } from '@/lib/money';

export default function ProcedimentosPage() {
  return (
    <RequireRole roles={['admin', 'receptionist', 'dentist']}>
      <ProceduresView />
    </RequireRole>
  );
}

interface FormState {
  code: string;
  name: string;
  price: string;
  description: string;
  requiresTooth: boolean;
  isActive: boolean;
}

const EMPTY_FORM: FormState = {
  code: '',
  name: '',
  price: '',
  description: '',
  requiresTooth: false,
  isActive: true,
};

function ProceduresView() {
  const { user } = useAuth();
  const isAdmin = user?.role === 'admin';

  const [items, setItems] = useState<Procedure[]>([]);
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [editing, setEditing] = useState<Procedure | null>(null);
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState<FormState>(EMPTY_FORM);
  const [formError, setFormError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      setItems((await listProcedures({ search: search.trim() || undefined })).data);
    } catch (err) {
      setError(extractApiError(err));
    } finally {
      setLoading(false);
    }
  }, [search]);

  useEffect(() => {
    const timer = setTimeout(load, 250);
    return () => clearTimeout(timer);
  }, [load]);

  function openForm(procedure?: Procedure) {
    setEditing(procedure ?? null);
    setForm(
      procedure
        ? {
            code: procedure.code,
            name: procedure.name,
            price: centsToInput(procedure.defaultPriceCents),
            description: procedure.description ?? '',
            requiresTooth: procedure.requiresTooth,
            isActive: procedure.isActive,
          }
        : EMPTY_FORM,
    );
    setFormError(null);
    setOpen(true);
  }

  async function save(e: React.FormEvent) {
    e.preventDefault();
    const priceCents = parseMoneyToCents(form.price);
    if (!form.code.trim() || form.name.trim().length < 3) {
      setFormError('Informe o código e o nome (mínimo 3 caracteres).');
      return;
    }
    if (priceCents === null) {
      setFormError('Informe um preço válido (ex.: 250,00).');
      return;
    }

    setSaving(true);
    setFormError(null);
    const input = {
      code: form.code.trim().toUpperCase(),
      name: form.name.trim(),
      description: form.description.trim() || undefined,
      defaultPriceCents: priceCents,
      requiresTooth: form.requiresTooth,
      isActive: form.isActive,
    };
    try {
      if (editing) await updateProcedure(editing.id, input);
      else await createProcedure(input);
      setOpen(false);
      load();
    } catch (err) {
      setFormError(extractApiError(err));
    } finally {
      setSaving(false);
    }
  }

  async function handleRemove(procedure: Procedure) {
    const confirmation = await Swal.fire({
      icon: 'warning',
      title: 'Remover procedimento?',
      text: `${procedure.code} — ${procedure.name}. Planos existentes não são afetados.`,
      showCancelButton: true,
      confirmButtonText: 'Remover',
      cancelButtonText: 'Cancelar',
      confirmButtonColor: '#dc3545',
    });
    if (!confirmation.isConfirmed) return;
    try {
      await removeProcedure(procedure.id);
      load();
    } catch (err) {
      Swal.fire({ icon: 'error', title: 'Erro', text: extractApiError(err) });
    }
  }

  return (
    <>
      <PageHeader
        title="Procedimentos"
        subtitle="Catálogo e preços de referência usados nos orçamentos"
        action={
          isAdmin && (
            <button type="button" className="btn btn-primary" onClick={() => openForm()}>
              <i className="bi bi-plus-lg me-1" />
              Novo procedimento
            </button>
          )
        }
      />

      <div className="row g-2 mb-3">
        <div className="col-12 col-md-5">
          <div className="input-group">
            <span className="input-group-text">
              <i className="bi bi-search" />
            </span>
            <input
              className="form-control"
              placeholder="Buscar por nome ou código"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              aria-label="Buscar procedimento"
            />
          </div>
        </div>
      </div>

      {error && <ErrorAlert message={error} onRetry={load} />}

      {loading ? (
        <Loading />
      ) : items.length === 0 ? (
        <EmptyState
          icon="bi-list-check"
          title="Nenhum procedimento encontrado"
          description={isAdmin ? 'Cadastre os procedimentos que a clínica realiza.' : undefined}
        />
      ) : (
        <div className="card border-0 shadow-sm">
          <div className="table-responsive">
            <table className="table table-hover align-middle mb-0">
              <thead className="table-light">
                <tr>
                  <th scope="col">Código</th>
                  <th scope="col">Procedimento</th>
                  <th scope="col" className="text-end">Preço</th>
                  <th scope="col">Dente</th>
                  <th scope="col">Status</th>
                  {isAdmin && <th scope="col" className="text-end">Ações</th>}
                </tr>
              </thead>
              <tbody>
                {items.map((p) => (
                  <tr key={p.id}>
                    <td>
                      <code>{p.code}</code>
                    </td>
                    <td className="fw-semibold">
                      {p.name}
                      {p.description && (
                        <small className="d-block text-muted fw-normal">{p.description}</small>
                      )}
                    </td>
                    <td className="text-end table-nowrap">{formatCents(p.defaultPriceCents)}</td>
                    <td>{p.requiresTooth ? 'Obrigatório' : '—'}</td>
                    <td>
                      <span className={`badge ${p.isActive ? 'text-bg-success' : 'text-bg-secondary'}`}>
                        {p.isActive ? 'Ativo' : 'Inativo'}
                      </span>
                    </td>
                    {isAdmin && (
                      <td className="text-end table-nowrap">
                        <button
                          className="btn btn-sm btn-outline-secondary me-1"
                          onClick={() => openForm(p)}
                          aria-label={`Editar ${p.name}`}
                        >
                          <i className="bi bi-pencil" />
                        </button>
                        <button
                          className="btn btn-sm btn-outline-danger"
                          onClick={() => handleRemove(p)}
                          aria-label={`Remover ${p.name}`}
                        >
                          <i className="bi bi-trash" />
                        </button>
                      </td>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      <Modal
        open={open}
        title={editing ? 'Editar procedimento' : 'Novo procedimento'}
        onClose={() => setOpen(false)}
        busy={saving}
        footer={
          <>
            <button className="btn btn-outline-secondary" onClick={() => setOpen(false)} disabled={saving}>
              Cancelar
            </button>
            <button type="submit" form="procedure-form" className="btn btn-primary" disabled={saving}>
              {saving && <span className="spinner-border spinner-border-sm me-2" />}
              Salvar
            </button>
          </>
        }
      >
        <form id="procedure-form" onSubmit={save} noValidate>
          {formError && <div className="alert alert-danger py-2">{formError}</div>}
          <div className="row g-3">
            <div className="col-5">
              <label htmlFor="proc-code" className="form-label">Código *</label>
              <input
                id="proc-code"
                className="form-control text-uppercase"
                value={form.code}
                maxLength={30}
                onChange={(e) => setForm({ ...form, code: e.target.value })}
              />
            </div>
            <div className="col-7">
              <label htmlFor="proc-price" className="form-label">Preço de referência (R$) *</label>
              <input
                id="proc-price"
                inputMode="decimal"
                className="form-control"
                placeholder="250,00"
                value={form.price}
                onChange={(e) => setForm({ ...form, price: e.target.value })}
              />
            </div>
            <div className="col-12">
              <label htmlFor="proc-name" className="form-label">Nome *</label>
              <input
                id="proc-name"
                className="form-control"
                maxLength={150}
                value={form.name}
                onChange={(e) => setForm({ ...form, name: e.target.value })}
              />
            </div>
            <div className="col-12">
              <label htmlFor="proc-desc" className="form-label">Descrição</label>
              <textarea
                id="proc-desc"
                className="form-control"
                rows={2}
                value={form.description}
                onChange={(e) => setForm({ ...form, description: e.target.value })}
              />
            </div>
            <div className="col-12">
              <div className="form-check form-switch">
                <input
                  id="proc-tooth"
                  type="checkbox"
                  className="form-check-input"
                  checked={form.requiresTooth}
                  onChange={(e) => setForm({ ...form, requiresTooth: e.target.checked })}
                />
                <label htmlFor="proc-tooth" className="form-check-label">
                  Exige indicar o dente no orçamento
                </label>
              </div>
              <div className="form-check form-switch">
                <input
                  id="proc-active"
                  type="checkbox"
                  className="form-check-input"
                  checked={form.isActive}
                  onChange={(e) => setForm({ ...form, isActive: e.target.checked })}
                />
                <label htmlFor="proc-active" className="form-check-label">Ativo</label>
              </div>
            </div>
          </div>
        </form>
      </Modal>
    </>
  );
}
