'use client';

import React from 'react';
import {
  Layers, Plus, Pencil, Trash2, ChevronDown, ChevronRight,
  Users, Loader2, Power,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { useSectorsLogic } from '../../hooks/useSectorsLogic';
import { PageHeader, Button, Badge, Toast } from '@/components/ui';

export default function SectorsPage() {
  const {
    sectors, loading,

    newSectorName, setNewSectorName,
    newSectorOpen, setNewSectorOpen,
    savingSector, createSector,

    editingSector, editSectorName, setEditSectorName,
    savingEditSector, openEditSector, saveEditSector,
    setEditingSector,

    toggleSectorActive, deleteSector, toggleExpand,

    newTeamSectorId, newTeamName, setNewTeamName,
    savingTeam, openNewTeam, createTeam,
    setNewTeamSectorId,

    editingTeam, editTeamName, setEditTeamName,
    savingEditTeam, openEditTeam, saveEditTeam,
    setEditingTeam,

    deleteTeam,

    toast,
  } = useSectorsLogic()

  const [confirmDelete, setConfirmDelete] = React.useState<{ type: 'sector' | 'team'; sectorId: string; teamId?: string; name: string } | null>(null)

  return (
    <div className="flex-1 overflow-y-auto p-6 md:p-10">
      <PageHeader
        icon={Layers}
        title="Setores"
        titleAccent=" & Equipes"
        subtitle="Organização para distribuição de atendimentos"
        actions={
          <Button
            variant="primary"
            size="sm"
            icon={<Plus className="w-3.5 h-3.5" />}
            onClick={() => setNewSectorOpen(true)}
          >
            Novo Setor
          </Button>
        }
      />

      {/* ── New sector inline form ────────────────────────────────────────── */}
      <AnimatePresence>
        {newSectorOpen && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            className="mb-6 overflow-hidden"
          >
            <div className="glass rounded-2xl border border-white/10 p-5 flex items-center gap-3">
              <input
                type="text"
                value={newSectorName}
                onChange={(e) => setNewSectorName(e.target.value)}
                placeholder="Nome do setor…"
                autoFocus
                onKeyDown={(e) => { if (e.key === 'Enter') createSector(); if (e.key === 'Escape') setNewSectorOpen(false) }}
                className="flex-1 bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-brand-500/50 transition-colors"
              />
              <Button variant="primary" size="sm" loading={savingSector} onClick={createSector} disabled={!newSectorName.trim()}>
                Criar
              </Button>
              <Button variant="ghost" size="sm" onClick={() => { setNewSectorOpen(false); setNewSectorName('') }}>
                Cancelar
              </Button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* ── Sectors list ─────────────────────────────────────────────────── */}
      {loading && sectors.length === 0 ? (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="w-6 h-6 text-brand-400 animate-spin" />
        </div>
      ) : sectors.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-20 gap-3">
          <Layers className="w-10 h-10 text-slate-600" />
          <p className="text-slate-500 text-sm">Nenhum setor criado ainda.</p>
          <Button variant="primary" size="sm" icon={<Plus className="w-3.5 h-3.5" />} onClick={() => setNewSectorOpen(true)}>
            Criar primeiro setor
          </Button>
        </div>
      ) : (
        <div className="space-y-3">
          {sectors.map((sector) => (
            <motion.div
              key={sector.id}
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              className="glass rounded-2xl border border-white/5 overflow-hidden"
            >
              {/* Sector header row */}
              <div className="flex items-center gap-3 p-4">
                <button
                  onClick={() => toggleExpand(sector.id)}
                  className="text-slate-400 hover:text-white transition-colors"
                >
                  {sector.expanded
                    ? <ChevronDown className="w-4 h-4" />
                    : <ChevronRight className="w-4 h-4" />}
                </button>

                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="text-white font-semibold">{sector.name}</span>
                    {!sector.isActive && <Badge variant="neutral">Inativo</Badge>}
                  </div>
                  <p className="text-xs text-slate-500 mt-0.5">
                    {sector._count?.teams ?? 0} equipes · {sector._count?.protocols ?? 0} protocolos
                  </p>
                </div>

                <div className="flex items-center gap-1">
                  <button
                    title="Adicionar equipe"
                    onClick={() => { openNewTeam(sector.id); if (!sector.expanded) toggleExpand(sector.id) }}
                    className="p-1.5 rounded-lg text-slate-400 hover:text-brand-400 hover:bg-brand-500/10 transition-colors"
                  >
                    <Plus className="w-3.5 h-3.5" />
                  </button>
                  <button
                    title="Editar setor"
                    onClick={() => openEditSector(sector)}
                    className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-white/10 transition-colors"
                  >
                    <Pencil className="w-3.5 h-3.5" />
                  </button>
                  <button
                    title={sector.isActive ? 'Desativar' : 'Ativar'}
                    onClick={() => toggleSectorActive(sector)}
                    className={`p-1.5 rounded-lg transition-colors ${
                      sector.isActive
                        ? 'text-slate-400 hover:text-amber-400 hover:bg-amber-500/10'
                        : 'text-emerald-400 hover:bg-emerald-500/10'
                    }`}
                  >
                    <Power className="w-3.5 h-3.5" />
                  </button>
                  <button
                    title="Excluir setor"
                    onClick={() => setConfirmDelete({ type: 'sector', sectorId: sector.id, name: sector.name })}
                    className="p-1.5 rounded-lg text-slate-400 hover:text-red-400 hover:bg-red-500/10 transition-colors"
                  >
                    <Trash2 className="w-3.5 h-3.5" />
                  </button>
                </div>
              </div>

              {/* Teams list (expanded) */}
              <AnimatePresence>
                {sector.expanded && (
                  <motion.div
                    initial={{ height: 0, opacity: 0 }}
                    animate={{ height: 'auto', opacity: 1 }}
                    exit={{ height: 0, opacity: 0 }}
                    className="overflow-hidden border-t border-white/5"
                  >
                    <div className="px-4 py-3 space-y-2">
                      {sector.teamsLoading ? (
                        <div className="flex items-center gap-2 py-2">
                          <Loader2 className="w-3.5 h-3.5 text-brand-400 animate-spin" />
                          <span className="text-xs text-slate-500">Carregando equipes…</span>
                        </div>
                      ) : sector.teams.length === 0 && newTeamSectorId !== sector.id ? (
                        <p className="text-xs text-slate-500 py-2">
                          Nenhuma equipe ainda.{' '}
                          <button onClick={() => openNewTeam(sector.id)} className="text-brand-400 hover:underline">
                            Adicionar equipe
                          </button>
                        </p>
                      ) : (
                        sector.teams.map((team) => (
                          <div key={team.id} className="flex items-center gap-3 px-3 py-2 rounded-xl bg-white/3 group">
                            <Users className="w-3.5 h-3.5 text-slate-500 shrink-0" />
                            <span className={`text-sm flex-1 ${team.isActive ? 'text-white' : 'text-slate-500 line-through'}`}>
                              {team.name}
                            </span>
                            <span className="text-xs text-slate-600">
                              {team._count?.protocols ?? 0} protocolos
                            </span>
                            <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                              <button
                                onClick={() => openEditTeam(team, sector.id)}
                                className="p-1 rounded text-slate-400 hover:text-white hover:bg-white/10 transition-colors"
                              >
                                <Pencil className="w-3 h-3" />
                              </button>
                              <button
                                onClick={() => setConfirmDelete({ type: 'team', sectorId: sector.id, teamId: team.id, name: team.name })}
                                className="p-1 rounded text-slate-400 hover:text-red-400 hover:bg-red-500/10 transition-colors"
                              >
                                <Trash2 className="w-3 h-3" />
                              </button>
                            </div>
                          </div>
                        ))
                      )}

                      {/* Inline new team form */}
                      {newTeamSectorId === sector.id && (
                        <div className="flex items-center gap-2 px-1">
                          <Users className="w-3.5 h-3.5 text-slate-500 shrink-0" />
                          <input
                            type="text"
                            value={newTeamName}
                            onChange={(e) => setNewTeamName(e.target.value)}
                            placeholder="Nome da equipe…"
                            autoFocus
                            onKeyDown={(e) => { if (e.key === 'Enter') createTeam(); if (e.key === 'Escape') setNewTeamSectorId(null) }}
                            className="flex-1 bg-white/5 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-brand-500/50 transition-colors"
                          />
                          <Button variant="primary" size="sm" loading={savingTeam} onClick={createTeam} disabled={!newTeamName.trim()} className="text-xs px-2 py-1">
                            Criar
                          </Button>
                          <button onClick={() => setNewTeamSectorId(null)} className="text-xs text-slate-500 hover:text-white">✕</button>
                        </div>
                      )}
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </motion.div>
          ))}
        </div>
      )}

      {/* Edit sector modal */}
      <AnimatePresence>
        {editingSector && (
          <motion.div
            initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
            onClick={() => setEditingSector(null)}
          >
            <motion.div
              initial={{ scale: 0.95 }} animate={{ scale: 1 }} exit={{ scale: 0.95 }}
              onClick={(e) => e.stopPropagation()}
              className="glass rounded-2xl border border-white/10 p-6 w-full max-w-sm space-y-4"
            >
              <h3 className="text-white font-bold text-base">Editar setor</h3>
              <input
                type="text"
                value={editSectorName}
                onChange={(e) => setEditSectorName(e.target.value)}
                autoFocus
                onKeyDown={(e) => { if (e.key === 'Enter') saveEditSector() }}
                className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-brand-500/50 transition-colors"
              />
              <div className="flex gap-2">
                <Button variant="secondary" size="sm" onClick={() => setEditingSector(null)} className="flex-1">Cancelar</Button>
                <Button variant="primary" size="sm" loading={savingEditSector} onClick={saveEditSector} className="flex-1">Salvar</Button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Edit team modal */}
      <AnimatePresence>
        {editingTeam && (
          <motion.div
            initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
            onClick={() => setEditingTeam(null)}
          >
            <motion.div
              initial={{ scale: 0.95 }} animate={{ scale: 1 }} exit={{ scale: 0.95 }}
              onClick={(e) => e.stopPropagation()}
              className="glass rounded-2xl border border-white/10 p-6 w-full max-w-sm space-y-4"
            >
              <h3 className="text-white font-bold text-base">Editar equipe</h3>
              <input
                type="text"
                value={editTeamName}
                onChange={(e) => setEditTeamName(e.target.value)}
                autoFocus
                onKeyDown={(e) => { if (e.key === 'Enter') saveEditTeam() }}
                className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-brand-500/50 transition-colors"
              />
              <div className="flex gap-2">
                <Button variant="secondary" size="sm" onClick={() => setEditingTeam(null)} className="flex-1">Cancelar</Button>
                <Button variant="primary" size="sm" loading={savingEditTeam} onClick={saveEditTeam} className="flex-1">Salvar</Button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Confirm delete */}
      <AnimatePresence>
        {confirmDelete && (
          <motion.div
            initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
            onClick={() => setConfirmDelete(null)}
          >
            <motion.div
              initial={{ scale: 0.95 }} animate={{ scale: 1 }} exit={{ scale: 0.95 }}
              onClick={(e) => e.stopPropagation()}
              className="glass rounded-2xl border border-white/10 p-6 w-full max-w-sm space-y-4"
            >
              <h3 className="text-white font-bold text-base">
                Remover {confirmDelete.type === 'sector' ? 'setor' : 'equipe'}?
              </h3>
              <p className="text-slate-400 text-sm">
                <strong className="text-white">{confirmDelete.name}</strong> será removido permanentemente.
                {confirmDelete.type === 'sector' && ' Todas as equipes do setor serão removidas.'}
              </p>
              <div className="flex gap-2">
                <Button variant="secondary" size="sm" onClick={() => setConfirmDelete(null)} className="flex-1">Cancelar</Button>
                <Button
                  variant="danger"
                  size="sm"
                  onClick={() => {
                    if (confirmDelete.type === 'sector') {
                      deleteSector(confirmDelete.sectorId)
                    } else if (confirmDelete.teamId) {
                      deleteTeam(confirmDelete.sectorId, confirmDelete.teamId)
                    }
                    setConfirmDelete(null)
                  }}
                  className="flex-1"
                >
                  Remover
                </Button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      <Toast message={toast?.message ?? ''} type={toast?.type ?? 'success'} visible={!!toast} />
    </div>
  )
}
