import { useEffect, useState } from 'react'
import { Link } from '@tanstack/react-router'
import { Building2, Plus } from 'lucide-react'
import { supabase } from '@/lib/supabase'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetFooter,
} from '@/components/ui/sheet'

interface OrgRow {
  id: string
  name: string
  is_provider: boolean
  created_at: string
  processes: [{ count: number }]
  users: [{ count: number }]
}

function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString('es-PY', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
  })
}

export function OrganizationsPage() {
  const [orgs, setOrgs] = useState<OrgRow[]>([])
  const [loading, setLoading] = useState(true)
  const [createOpen, setCreateOpen] = useState(false)
  const [orgName, setOrgName] = useState('')
  const [createError, setCreateError] = useState<string | null>(null)
  const [creating, setCreating] = useState(false)

  const fetchOrgs = async () => {
    const { data } = await supabase
      .from('organizations')
      .select('id, name, is_provider, created_at, processes:processes(count), users:users(count)')
      .order('name')

    const sorted = ((data as OrgRow[] | null) ?? []).sort((a, b) => {
      if (a.is_provider && !b.is_provider) return -1
      if (!a.is_provider && b.is_provider) return 1
      return a.name.localeCompare(b.name)
    })

    setOrgs(sorted)
    setLoading(false)
  }

  useEffect(() => { void fetchOrgs() }, [])

  const openCreate = () => {
    setOrgName('')
    setCreateError(null)
    setCreateOpen(true)
  }

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault()
    const trimmed = orgName.trim()
    if (!trimmed) {
      setCreateError('El nombre es requerido')
      return
    }
    setCreating(true)
    const { error } = await supabase
      .from('organizations')
      .insert({ name: trimmed, is_provider: false })
    if (error) {
      setCreateError(
        error.message.toLowerCase().includes('duplicate') || error.message.toLowerCase().includes('unique')
          ? 'Ya existe una organización con ese nombre'
          : error.message
      )
      setCreating(false)
    } else {
      setCreateOpen(false)
      setCreating(false)
      void fetchOrgs()
    }
  }

  return (
    <>
      <div className="flex items-center justify-between mb-5">
        <h2 className="text-lg font-semibold text-slate-900">Organizaciones</h2>
        <Button size="sm" onClick={openCreate}>
          <Plus className="h-4 w-4 mr-1.5" />
          Nueva organización
        </Button>
      </div>

      {loading ? (
        <TableSkeleton rows={5} />
      ) : orgs.length === 0 ? (
        <EmptyState
          icon={<Building2 className="h-10 w-10 text-slate-300" />}
          message="No hay organizaciones clientes aún. Creá la primera con el botón de arriba."
        />
      ) : (
        <div className="rounded-lg border border-slate-200 overflow-hidden bg-white">
          <table className="w-full text-sm">
            <thead className="bg-slate-50 border-b border-slate-200">
              <tr>
                <th className="text-left py-2.5 px-4 font-medium text-slate-600">Organización</th>
                <th className="text-right py-2.5 px-4 font-medium text-slate-600">Procesos</th>
                <th className="text-right py-2.5 px-4 font-medium text-slate-600">Usuarios</th>
                <th className="text-left py-2.5 px-4 font-medium text-slate-600">Creada</th>
                <th className="py-2.5 px-4" />
              </tr>
            </thead>
            <tbody>
              {orgs.map((org) => (
                <tr key={org.id} className="border-b border-slate-100 last:border-0 hover:bg-slate-50/50 transition-colors">
                  <td className="py-3 px-4 font-medium text-slate-900">
                    <div className="flex items-center gap-2">
                      {org.name}
                      {org.is_provider && (
                        <span className="text-[10px] font-semibold px-1.5 py-0.5 rounded-full border"
                          style={{ color: '#F59845', background: '#fff8f0', borderColor: '#fcd9aa' }}>
                          InQuality
                        </span>
                      )}
                    </div>
                  </td>
                  <td className="py-3 px-4 text-right text-slate-600 tabular-nums">
                    {org.processes[0]?.count ?? 0}
                  </td>
                  <td className="py-3 px-4 text-right text-slate-600 tabular-nums">
                    {org.users[0]?.count ?? 0}
                  </td>
                  <td className="py-3 px-4 text-slate-500">{formatDate(org.created_at)}</td>
                  <td className="py-3 px-4 text-right">
                    <Link
                      to="/admin/organizations/$orgId"
                      params={{ orgId: org.id }}
                      className="text-xs font-semibold text-[#F59845] hover:text-[#e0872e] transition-colors"
                    >
                      Ver detalle →
                    </Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <Sheet open={createOpen} onOpenChange={setCreateOpen}>
        <SheetContent>
          <SheetHeader>
            <SheetTitle>Nueva organización</SheetTitle>
          </SheetHeader>
          <form onSubmit={handleCreate} className="mt-5 flex flex-col gap-4">
            <div className="flex flex-col gap-1.5">
              <Label htmlFor="create-org-name">Nombre</Label>
              <Input
                id="create-org-name"
                value={orgName}
                onChange={(e) => setOrgName(e.target.value)}
                placeholder="ej. Banco Solar SA"
                disabled={creating}
                autoFocus
              />
              {createError && <p className="text-xs text-red-600">{createError}</p>}
            </div>
            <SheetFooter className="mt-2">
              <Button type="submit" disabled={creating}>
                {creating ? 'Creando…' : 'Crear organización'}
              </Button>
            </SheetFooter>
          </form>
        </SheetContent>
      </Sheet>
    </>
  )
}

function TableSkeleton({ rows }: { rows: number }) {
  return (
    <div className="rounded-lg border border-slate-200 overflow-hidden">
      <div className="bg-slate-50 border-b border-slate-200 h-10" />
      <div className="flex flex-col divide-y divide-slate-100">
        {Array.from({ length: rows }).map((_, i) => (
          <div key={i} className="flex gap-4 px-4 py-3 bg-white">
            <Skeleton className="h-4 flex-1" />
            <Skeleton className="h-4 w-12" />
            <Skeleton className="h-4 w-12" />
            <Skeleton className="h-4 w-24" />
            <Skeleton className="h-4 w-16" />
          </div>
        ))}
      </div>
    </div>
  )
}

function EmptyState({ icon, message }: { icon: React.ReactNode; message: string }) {
  return (
    <div className="flex flex-col items-center justify-center py-20 gap-3 text-center">
      {icon}
      <p className="text-sm text-slate-500 max-w-xs">{message}</p>
    </div>
  )
}
