import { useCallback, useEffect, useRef, useState } from 'react';
import {
  FolderOpen, RefreshCw, ChevronRight, Cloud, Download,
  Play, Rocket, Flame, X, ExternalLink, Ban, Clock,
} from 'lucide-react';
import { useAppStore } from '@/stores/app';
import { useI18n } from '@/i18n';
import { terraformApi, type Workspace, type WsStatus } from '@/api/endpoints/terraform';

/* ── helpers ── */

type FilterKey = 'all' | 'active' | 'draft' | 'failed' | 'destroyed';

const RUNNING: WsStatus[] = ['planning', 'applying', 'destroying'];
const ACTIVE: WsStatus[] = ['applied', 'planned', 'planning', 'applying'];

function dateLabel(dt: string | undefined): string {
  const tFn = useI18n.getState().t;
  if (!dt) return tFn('ws.noDate');
  const slice = dt.slice(0, 10);
  const today = new Date().toISOString().slice(0, 10);
  const yesterday = new Date(Date.now() - 86400000).toISOString().slice(0, 10);
  if (slice === today) return tFn('chat.today');
  if (slice === yesterday) return tFn('chat.yesterday');
  const d = new Date(slice + 'T00:00:00');
  const diff = Math.floor((Date.now() - d.getTime()) / 86400000);
  if (diff < 7) return d.toLocaleDateString('pt-BR', { weekday: 'long' });
  return d.toLocaleDateString('pt-BR', { day: '2-digit', month: 'short', year: 'numeric' });
}

function timeAgo(ts: string | undefined): string {
  if (!ts) return '—';
  const d = new Date(ts + 'Z');
  const s = Math.floor((Date.now() - d.getTime()) / 1000);
  const tFn = useI18n.getState().t;
  if (s < 60) return tFn('chat.timeNow');
  if (s < 3600) return Math.floor(s / 60) + 'min';
  if (s < 86400) return Math.floor(s / 3600) + 'h';
  return Math.floor(s / 86400) + 'd';
}

const BADGE: Record<string, { cls: string; label: string }> = {
  draft:      { cls: 'bg-[var(--bg3)] text-[var(--t3)]', label: 'Draft' },
  planning:   { cls: 'bg-[var(--ppl)] text-[var(--pp)]', label: 'Planning...' },
  planned:    { cls: 'bg-[var(--gnl)] text-[var(--gn)]', label: 'Plan OK' },
  applying:   { cls: 'bg-[var(--bll)] text-[var(--bl)]', label: 'Applying...' },
  applied:    { cls: 'bg-[var(--gnl)] text-[var(--gn)]', label: 'Applied' },
  destroying: { cls: 'bg-[var(--rdl)] text-[var(--rd)]', label: 'Destroying...' },
  destroyed:  { cls: 'bg-[var(--bg3)] text-[var(--t4)]', label: 'Destroyed' },
  failed:     { cls: 'bg-[var(--rdl)] text-[var(--rd)]', label: 'Failed' },
};

function StatusBadge({ status }: { status: WsStatus }) {
  const b = BADGE[status] || BADGE.draft;
  return (
    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-[.68rem] font-semibold whitespace-nowrap ${b.cls}`}>
      {(RUNNING.includes(status)) && (
        <span className="inline-block w-2 h-2 rounded-full mr-1.5 animate-pulse"
          style={{ background: 'currentColor' }} />
      )}
      {b.label}
    </span>
  );
}

/* ── component ── */

export default function WorkspacesPage() {
  const ociCfg = useAppStore((s) => s.ociCfg);
  const { t } = useI18n();

  const [list, setList] = useState<Workspace[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<FilterKey>('all');
  const [closedGroups, setClosedGroups] = useState<Set<string>>(new Set());
  const [expanded, setExpanded] = useState<string | null>(null);

  /* confirm modals */
  const [confirmDestroy, setConfirmDestroy] = useState<string | null>(null);
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
  const [destroyInput, setDestroyInput] = useState('');

  const pollRef = useRef<Set<string>>(new Set());

  /* ── load ── */
  const load = useCallback(async () => {
    setLoading(true);
    try {
      const ws = await terraformApi.listWorkspaces();
      setList(ws);
    } catch {
      setList([]);
    }
    setLoading(false);
  }, []);

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

  /* ── polling ── */
  const pollWs = useCallback(async (wid: string) => {
    if (pollRef.current.has(wid)) return;
    pollRef.current.add(wid);
    for (let i = 0; i < 300; i++) {
      await new Promise((r) => setTimeout(r, 3000));
      try {
        const r = await terraformApi.status(wid);
        setList((prev) =>
          prev.map((w) =>
            w.id === wid
              ? {
                  ...w,
                  status: r.status,
                  plan_output: r.plan_output || w.plan_output,
                  apply_output: r.apply_output || w.apply_output,
                  destroy_output: r.destroy_output || w.destroy_output,
                  error: r.error || '',
                }
              : w,
          ),
        );
        if (!RUNNING.includes(r.status)) {
          pollRef.current.delete(wid);
          load();
          return;
        }
      } catch { /* keep polling */ }
    }
    pollRef.current.delete(wid);
  }, [load]);

  /* ── actions ── */
  const doPlan = async (wid: string) => {
    try { await terraformApi.plan(wid); } catch (e: unknown) { alert('Erro: ' + (e as Error).message); return; }
    load(); pollWs(wid);
  };
  const doApply = async (wid: string) => {
    try { await terraformApi.apply(wid); } catch (e: unknown) { alert('Erro: ' + (e as Error).message); return; }
    load(); pollWs(wid);
  };
  const doDestroy = async () => {
    if (!confirmDestroy || destroyInput !== 'DESTROY') return;
    const wid = confirmDestroy;
    setConfirmDestroy(null); setDestroyInput('');
    try { await terraformApi.destroy(wid); } catch (e: unknown) { alert('Erro: ' + (e as Error).message); load(); return; }
    load(); pollWs(wid);
  };
  const doDelete = async () => {
    if (!confirmDelete) return;
    const wid = confirmDelete;
    setConfirmDelete(null);
    try { await terraformApi.deleteWorkspace(wid); } catch (e: unknown) { alert('Erro: ' + (e as Error).message); }
    load();
  };
  const doCancel = async (wid: string) => {
    try { await terraformApi.cancel(wid); } catch { /* noop */ }
    load();
  };

  /* ── filter + group ── */
  let items = list;
  if (filter === 'active') items = list.filter((w) => ACTIVE.includes(w.status));
  else if (filter === 'destroyed') items = list.filter((w) => w.status === 'destroyed');
  else if (filter === 'failed') items = list.filter((w) => w.status === 'failed');
  else if (filter === 'draft') items = list.filter((w) => w.status === 'draft');

  const counts = {
    all: list.length,
    active: list.filter((w) => ACTIVE.includes(w.status)).length,
    draft: list.filter((w) => w.status === 'draft').length,
    failed: list.filter((w) => w.status === 'failed').length,
    destroyed: list.filter((w) => w.status === 'destroyed').length,
  };

  const groups: { label: string; date: string; items: Workspace[] }[] = [];
  const gMap: Record<string, number> = {};
  for (const w of items) {
    const dt = (w.updated_at || w.created_at || '').slice(0, 10);
    const label = dateLabel(dt);
    if (gMap[label] === undefined) { gMap[label] = groups.length; groups.push({ label, date: dt, items: [] }); }
    groups[gMap[label]].items.push(w);
  }

  const toggleGroup = (label: string) =>
    setClosedGroups((prev) => {
      const next = new Set(prev);
      if (next.has(label)) next.delete(label); else next.add(label);
      return next;
    });

  const ociName = (id: string) => {
    const oc = ociCfg.find((c) => c.id === id);
    return oc ? (oc.tenancy_name || oc.region || id) : '—';
  };

  /* ── render ── */
  return (
    <div className="page-full flex flex-col">
      {/* header */}
      <div className="flex items-center gap-3 px-5 py-3 border-b"
           style={{ borderColor: 'var(--bd)', background: 'var(--bg1)' }}>
        <FolderOpen size={20} style={{ color: 'var(--pp)' }} />
        <h2 className="text-base font-bold" style={{ color: 'var(--t1)' }}>{t('ws.title')}</h2>
        <div className="flex-1" />

        {/* filters */}
        <div className="flex gap-1">
          {([
            ['all', t('ws.all')],
            ['active', t('ws.active')],
            ['draft', t('ws.draft')],
            ['failed', t('ws.failed')],
            ['destroyed', t('ws.destroyed')],
          ] as [FilterKey, string][]).map(([k, l]) => (
            <button key={k} onClick={() => setFilter(k)}
              className="px-2.5 py-1 rounded-full text-[.68rem] font-medium transition-colors cursor-pointer"
              style={{
                background: filter === k ? 'var(--pp)' : 'var(--bg3)',
                color: filter === k ? '#fff' : 'var(--t3)',
                border: 'none',
              }}>
              {l} ({counts[k]})
            </button>
          ))}
        </div>

        <button onClick={load} disabled={loading}
          className="btn btn-secondary btn-sm">
          <RefreshCw size={13} className={loading ? 'animate-spin' : ''} />
          {loading ? t('ws.loading') : t('ws.refresh')}
        </button>
      </div>

      {/* body */}
      <div className="flex-1 overflow-y-auto p-4" style={{ background: 'var(--bg)' }}>
        {groups.length === 0 && !loading && (
          <div className="empty-state">
            <FolderOpen size={40} />
            <h3>{t('ws.noWs')}</h3>
            <p>{t('ws.noWsHint')}</p>
          </div>
        )}

        {groups.length === 0 && loading && (
          <div className="flex items-center justify-center py-16" style={{ color: 'var(--t4)' }}>
            <RefreshCw size={18} className="animate-spin mr-2" />
            <span className="text-sm">{t('ws.loadingWs')}</span>
          </div>
        )}

        {groups.map((g) => {
          const open = !closedGroups.has(g.label);
          return (
            <div key={g.label} className="mb-3">
              {/* group header */}
              <button onClick={() => toggleGroup(g.label)}
                className="flex items-center gap-2 w-full px-3 py-2 rounded-lg cursor-pointer transition-colors"
                style={{ background: 'var(--bg1)', border: '1px solid var(--bd)' }}>
                <ChevronRight size={14} className={`transition-transform ${open ? 'rotate-90' : ''}`}
                  style={{ color: 'var(--t3)' }} />
                <span className="text-[.78rem] font-semibold" style={{ color: 'var(--t1)' }}>{g.label}</span>
                <span className="text-[.66rem]" style={{ color: 'var(--t4)' }}>
                  {g.items.length} workspace{g.items.length > 1 ? 's' : ''}
                </span>
              </button>

              {/* group body */}
              {open && (
                <div className="mt-1 space-y-1 pl-1">
                  {g.items.map((w) => {
                    const running = RUNNING.includes(w.status);
                    const hasOutput = !!(w.plan_output || w.apply_output || w.destroy_output || w.error);
                    const isExpanded = expanded === w.id;
                    const title = w.session_title || w.name || 'workspace';

                    return (
                      <div key={w.id}>
                        {/* row */}
                        <div
                          className="flex items-center gap-3 px-3 py-2.5 rounded-lg cursor-pointer transition-colors group"
                          style={{ background: 'var(--bg2)', border: '1px solid var(--bd)' }}
                          onClick={() => {
                            if (hasOutput && !running) setExpanded(isExpanded ? null : w.id);
                          }}>
                          <StatusBadge status={w.status} />

                          <div className="flex-1 min-w-0">
                            <div className="text-[.78rem] font-medium truncate" style={{ color: 'var(--t1)' }}
                              title={title}>
                              {title}
                            </div>
                            <div className="flex items-center gap-3 mt-0.5 text-[.66rem]" style={{ color: 'var(--t4)' }}>
                              <span className="flex items-center gap-1">
                                <Cloud size={10} /> {ociName(w.oci_config_id)}
                              </span>
                              {w.compartment_id && (
                                <span title={w.compartment_id}>...{w.compartment_id.slice(-8)}</span>
                              )}
                              <span className="flex items-center gap-1">
                                <Clock size={10} /> {timeAgo(w.updated_at || w.created_at)}
                              </span>
                              {hasOutput && !running && (
                                <span style={{ color: 'var(--pp)', cursor: 'pointer' }}>
                                  {isExpanded ? `▾ ${t('ws.hideOutput')}` : `▸ ${t('ws.viewOutput')}`}
                                </span>
                              )}
                            </div>
                          </div>

                          {/* actions */}
                          <div className="flex items-center gap-1.5" onClick={(e) => e.stopPropagation()}>
                            {running ? (
                              <ActionBtn color="var(--rd)" icon={<Ban size={12} />}
                                label={t('ws.cancel')} onClick={() => doCancel(w.id)} />
                            ) : (
                              <>
                                <ActionBtn color="var(--bg3)" textColor="var(--t2)"
                                  icon={<ExternalLink size={12} />} label={t('ws.open')}
                                  onClick={() => window.open(`/terraform?ws=${w.id}`, '_blank')} />

                                {['draft', 'failed', 'destroyed', 'planned', 'applied'].includes(w.status) && (
                                  <ActionBtn color="var(--pp)" icon={<Play size={12} />}
                                    label={t('ws.plan')} onClick={() => doPlan(w.id)} />
                                )}

                                {w.status === 'planned' && (
                                  <ActionBtn color="var(--gn)" icon={<Rocket size={12} />}
                                    label={t('ws.apply')} onClick={() => doApply(w.id)} />
                                )}

                                {(w.status === 'applied' || w.status === 'planned') && (
                                  <ActionBtn color="var(--rd)" icon={<Flame size={12} />}
                                    label={t('ws.destroy')} onClick={() => { setConfirmDestroy(w.id); setDestroyInput(''); }} />
                                )}

                                <ActionBtn color="transparent" textColor="var(--rd)"
                                  borderColor="var(--rd)" icon={<X size={12} />}
                                  label="" title={t('ws.delete')}
                                  onClick={() => setConfirmDelete(w.id)} />

                                <a href={terraformApi.downloadUrl(w.id)}
                                  className="flex items-center gap-1 px-2 py-1 rounded-md text-[.66rem] font-medium transition-colors cursor-pointer"
                                  style={{ background: 'var(--bg3)', color: 'var(--t3)', border: '1px solid var(--bd)' }}
                                  title="Download ZIP" download
                                  onClick={(e) => e.stopPropagation()}>
                                  <Download size={12} />
                                </a>
                              </>
                            )}
                          </div>
                        </div>

                        {/* expanded output */}
                        {isExpanded && hasOutput && (
                          <div className="mt-1 ml-4 rounded-lg overflow-hidden"
                               style={{ border: '1px solid var(--bd)', background: 'var(--bg1)' }}>
                            <pre className="p-3 text-[.68rem] overflow-auto max-h-80 whitespace-pre-wrap"
                                 style={{ color: w.error ? 'var(--rd)' : 'var(--t2)', fontFamily: 'var(--fm)' }}>
                              {w.error
                                ? 'ERROR: ' + w.error
                                : (w.destroy_output || w.apply_output || w.plan_output || '')}
                            </pre>
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Destroy confirm modal */}
      {confirmDestroy && (
        <Modal onClose={() => setConfirmDestroy(null)}>
          <h3 className="text-sm font-bold mb-2" style={{ color: 'var(--t1)' }}>{t('ws.confirmDestroy')}</h3>
          <p className="text-[.76rem] mb-3" style={{ color: 'var(--t2)' }}>
            {t('ws.confirmDestroyMsg')}
            {' '}
            Digite <strong>DESTROY</strong> para confirmar:
          </p>
          <input type="text" value={destroyInput}
            onChange={(e) => setDestroyInput(e.target.value)}
            placeholder="DESTROY"
            className="w-full px-3 py-2 rounded-lg text-sm text-center"
            style={{
              background: 'var(--bg2)', color: 'var(--t1)',
              border: `1px solid ${destroyInput === 'DESTROY' ? 'var(--gn)' : 'var(--rd)'}`,
            }}
            autoFocus
            onKeyDown={(e) => { if (e.key === 'Enter') doDestroy(); }}
          />
          <div className="flex justify-end gap-2 mt-3">
            <button onClick={() => setConfirmDestroy(null)} className="btn btn-secondary btn-sm">
              {t('common.cancel')}
            </button>
            <button onClick={doDestroy} disabled={destroyInput !== 'DESTROY'}
              className="btn btn-sm" style={{ background: 'var(--rd)', color: '#fff', borderColor: 'var(--rd)' }}>
              {t('ws.destroy')}
            </button>
          </div>
        </Modal>
      )}

      {/* Delete confirm modal */}
      {confirmDelete && (
        <Modal onClose={() => setConfirmDelete(null)}>
          <h3 className="text-sm font-bold mb-2" style={{ color: 'var(--t1)' }}>{t('ws.deleteWs')}</h3>
          <p className="text-[.76rem] mb-3" style={{ color: 'var(--t2)' }}>
            {t('ws.deleteWsMsg')}
          </p>
          <div className="flex justify-end gap-2 mt-3">
            <button onClick={() => setConfirmDelete(null)} className="btn btn-secondary btn-sm">
              {t('common.cancel')}
            </button>
            <button onClick={doDelete} className="btn btn-sm"
              style={{ background: 'var(--rd)', color: '#fff', borderColor: 'var(--rd)' }}>
              {t('ws.delete')}
            </button>
          </div>
        </Modal>
      )}
    </div>
  );
}

/* ── Small shared components ── */

function ActionBtn({
  color, textColor, borderColor, icon, label, title, onClick,
}: {
  color: string; textColor?: string; borderColor?: string;
  icon: React.ReactNode; label: string; title?: string;
  onClick: () => void;
}) {
  return (
    <button onClick={onClick} title={title || label}
      className="flex items-center gap-1 px-2 py-1 rounded-md text-[.66rem] font-medium transition-colors cursor-pointer"
      style={{
        background: color,
        color: textColor || '#fff',
        border: `1px solid ${borderColor || color}`,
      }}>
      {icon}
      {label && <span>{label}</span>}
    </button>
  );
}

function Modal({ children, onClose }: { children: React.ReactNode; onClose: () => void }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center"
         style={{ background: 'rgba(0,0,0,.55)' }} onClick={onClose}>
      <div className="w-full max-w-sm rounded-xl p-5 animate-[fadeIn_.2s_ease]"
           style={{ background: 'var(--bg1)', border: '1px solid var(--bd)', boxShadow: 'var(--sh3)' }}
           onClick={(e) => e.stopPropagation()}>
        {children}
      </div>
    </div>
  );
}
