'use client';

import { CrudToolbar, ManagementTable, Panel, StatCard } from '@chego/ui';
import { FormEvent, useEffect, useMemo, useState } from 'react';
import { currency, fetchWithSession, humanStatus, statusTone } from '../components/api-helpers';

type PromotionItem = {
  id: string;
  title: string;
  description?: string | null;
  discountType: 'PERCENTAGE' | 'FIXED' | 'FREE_DELIVERY';
  discountValue: number | string;
  startsAt: string;
  endsAt: string;
  isActive: boolean;
};

const emptyValues = {
  title: '',
  description: '',
  discountType: 'PERCENTAGE',
  discountValue: '',
  startsAt: '',
  endsAt: '',
  isActive: 'true',
};

export default function PromotionsPage() {
  const [items, setItems] = useState<PromotionItem[]>([]);
  const [values, setValues] = useState<Record<string, string>>(emptyValues);
  const [mode, setMode] = useState<'idle' | 'create' | 'edit'>('idle');
  const [editingId, setEditingId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const load = async () => {
    setLoading(true);
    setError('');
    try {
      setItems(await fetchWithSession('/promotions'));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Falha ao carregar promocoes.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void load();
  }, []);

  const metrics = useMemo(
    () => [
      { label: 'Promocoes ativas', value: String(items.filter((item) => item.isActive).length), hint: 'na vitrine agora', tone: 'emerald' as const },
      { label: 'Agendadas', value: String(items.filter((item) => new Date(item.startsAt) > new Date()).length), hint: 'entrada futura', tone: 'amber' as const },
      { label: 'Frete promocional', value: String(items.filter((item) => item.discountType === 'FREE_DELIVERY').length), hint: 'campanhas de entrega', tone: 'sky' as const },
      { label: 'Cadastro total', value: String(items.length), hint: 'campanhas da loja', tone: 'rose' as const },
    ],
    [items],
  );

  const resetForm = () => {
    setMode('idle');
    setEditingId(null);
    setValues(emptyValues);
    setSaving(false);
  };

  const submit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setSaving(true);
    setError('');
    try {
      await fetchWithSession(mode === 'create' ? '/promotions' : `/promotions/${editingId}`, {
        method: mode === 'create' ? 'POST' : 'PATCH',
        body: JSON.stringify({
          title: values.title,
          description: values.description || null,
          discountType: values.discountType,
          discountValue: Number(values.discountValue),
          startsAt: values.startsAt,
          endsAt: values.endsAt,
          isActive: values.isActive === 'true',
        }),
      });
      resetForm();
      await load();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Falha ao salvar promocao.');
      setSaving(false);
    }
  };

  const handleEdit = (item: PromotionItem) => {
    setMode('edit');
    setEditingId(item.id);
    setValues({
      title: item.title,
      description: item.description ?? '',
      discountType: item.discountType,
      discountValue: String(item.discountValue),
      startsAt: item.startsAt.slice(0, 16),
      endsAt: item.endsAt.slice(0, 16),
      isActive: item.isActive ? 'true' : 'false',
    });
  };

  const handleArchive = async (item: PromotionItem) => {
    if (!window.confirm(`Desativar promocao ${item.title}?`)) return;
    await fetchWithSession(`/promotions/${item.id}`, { method: 'DELETE' });
    await load();
  };

  return (
    <div className="space-y-6">
      <section className="grid gap-4 md:grid-cols-4">
        {metrics.map((metric) => <StatCard key={metric.label} {...metric} />)}
      </section>

      <Panel title="Promocoes da loja" eyebrow="Campanhas reais">
        <CrudToolbar filters={['desconto percentual', 'frete promocional', 'vitrine publica', 'campanha ativa']} />
        <div className="mt-4 flex gap-3">
          <button type="button" onClick={() => { setMode('create'); setEditingId(null); setValues(emptyValues); }} className="rounded-full border border-slate-900 bg-slate-900 px-4 py-2 text-xs font-bold uppercase tracking-[0.18em] text-white">Nova promocao</button>
          <button type="button" onClick={() => void load()} className="rounded-full border border-slate-200 bg-white px-4 py-2 text-xs font-bold uppercase tracking-[0.18em] text-slate-700">Recarregar</button>
        </div>
        {error ? <p className="mt-4 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">{error}</p> : null}
        {mode !== 'idle' ? (
          <form className="mt-5 grid gap-4 rounded-[1.5rem] border border-slate-200 bg-slate-50 p-5 md:grid-cols-2" onSubmit={submit}>
            <label className="grid gap-2 text-sm font-semibold text-slate-700">
              <span>Titulo</span>
              <input required value={values.title} onChange={(event) => setValues((current) => ({ ...current, title: event.target.value }))} className="h-12 rounded-2xl border border-slate-200 bg-white px-4 outline-none" />
            </label>
            <label className="grid gap-2 text-sm font-semibold text-slate-700">
              <span>Tipo</span>
              <select value={values.discountType} onChange={(event) => setValues((current) => ({ ...current, discountType: event.target.value }))} className="h-12 rounded-2xl border border-slate-200 bg-white px-4 outline-none">
                <option value="PERCENTAGE">Percentual</option>
                <option value="FIXED">Valor fixo</option>
                <option value="FREE_DELIVERY">Frete gratis</option>
              </select>
            </label>
            <label className="grid gap-2 text-sm font-semibold text-slate-700 md:col-span-2">
              <span>Descricao</span>
              <input value={values.description} onChange={(event) => setValues((current) => ({ ...current, description: event.target.value }))} className="h-12 rounded-2xl border border-slate-200 bg-white px-4 outline-none" />
            </label>
            <label className="grid gap-2 text-sm font-semibold text-slate-700">
              <span>Valor</span>
              <input required type="number" step="0.01" min="0" value={values.discountValue} onChange={(event) => setValues((current) => ({ ...current, discountValue: event.target.value }))} className="h-12 rounded-2xl border border-slate-200 bg-white px-4 outline-none" />
            </label>
            <label className="grid gap-2 text-sm font-semibold text-slate-700">
              <span>Status</span>
              <select value={values.isActive} onChange={(event) => setValues((current) => ({ ...current, isActive: event.target.value }))} className="h-12 rounded-2xl border border-slate-200 bg-white px-4 outline-none">
                <option value="true">Ativa</option>
                <option value="false">Inativa</option>
              </select>
            </label>
            <label className="grid gap-2 text-sm font-semibold text-slate-700">
              <span>Inicio</span>
              <input required type="datetime-local" value={values.startsAt} onChange={(event) => setValues((current) => ({ ...current, startsAt: event.target.value }))} className="h-12 rounded-2xl border border-slate-200 bg-white px-4 outline-none" />
            </label>
            <label className="grid gap-2 text-sm font-semibold text-slate-700">
              <span>Fim</span>
              <input required type="datetime-local" value={values.endsAt} onChange={(event) => setValues((current) => ({ ...current, endsAt: event.target.value }))} className="h-12 rounded-2xl border border-slate-200 bg-white px-4 outline-none" />
            </label>
            <div className="md:col-span-2 flex gap-3">
              <button type="submit" disabled={saving} className="rounded-full bg-slate-900 px-5 py-3 text-xs font-black uppercase tracking-[0.18em] text-white">{saving ? 'Salvando...' : mode === 'create' ? 'Criar promocao' : 'Salvar promocao'}</button>
              <button type="button" onClick={resetForm} className="rounded-full border border-slate-200 bg-white px-5 py-3 text-xs font-black uppercase tracking-[0.18em] text-slate-700">Cancelar</button>
            </div>
          </form>
        ) : null}
        <div className="mt-5">
          <ManagementTable
            columns={[
              { key: 'name', label: 'Campanha' },
              { key: 'type', label: 'Tipo' },
              { key: 'period', label: 'Periodo' },
              { key: 'discount', label: 'Desconto', align: 'right' },
              { key: 'status', label: 'Status' },
            ]}
            rows={items.map((item) => ({
              id: item.id,
              cells: {
                name: <div><p className="font-bold text-slate-900">{item.title}</p><p className="text-xs text-slate-500">{item.description ?? 'Sem descricao'}</p></div>,
                type: item.discountType === 'PERCENTAGE' ? 'Percentual' : item.discountType === 'FIXED' ? 'Valor fixo' : 'Frete gratis',
                period: `${new Date(item.startsAt).toLocaleDateString('pt-BR')} - ${new Date(item.endsAt).toLocaleDateString('pt-BR')}`,
                discount: <span className="font-semibold text-slate-900">{item.discountType === 'PERCENTAGE' ? `${item.discountValue}%` : currency(item.discountValue)}</span>,
                status: { value: humanStatus(item.isActive ? 'ACTIVE' : 'SUSPENDED'), tone: statusTone(item.isActive ? 'ACTIVE' : 'SUSPENDED'), badge: true },
              },
            }))}
            pageLabel={loading ? 'Carregando promocoes...' : `Mostrando ${items.length} promocoes desta loja`}
            getRowActions={(row) => {
              const item = items.find((entry) => entry.id === row.id);
              if (!item) return [];
              return [
                { label: 'Editar', onClick: () => handleEdit(item) },
                { label: 'Desativar', onClick: () => void handleArchive(item) },
              ];
            }}
          />
        </div>
      </Panel>
    </div>
  );
}
