'use client';

import { useEffect, useState, useCallback } from 'react';
import { api } from '@/lib/api';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { toast } from 'sonner';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import Link from 'next/link';
import { ShieldCheck, ShieldAlert, Eye } from 'lucide-react';

interface Professional {
  id: string;
  user_id: string;
  is_active: boolean;
  profession?: string;
  identification?: string;
  rethus_code?: string;
  rethus_validated?: boolean;
  rate?: number;
  users?: { id: string; name: string; email?: string; phone?: string };
}

export default function ProfessionalsPage() {
  const [approved, setApproved] = useState<Professional[]>([]);
  const [pending, setPending] = useState<Professional[]>([]);
  const [rejected, setRejected] = useState<Professional[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(() => {
    setLoading(true);
    setError(null);
    Promise.all([
      api.get<{ data: Professional[]; meta: any }>('/professionals').then((r) => r.data).catch(() => [] as Professional[]),
      api.get<{ data: Professional[]; meta: any }>('/professionals/pending').then((r) => r.data).catch(() => [] as Professional[]),
      api.get<{ data: Professional[]; meta: any }>('/professionals/rejected').then((r) => r.data).catch(() => [] as Professional[]),
    ])
      .then(([a, p, r]) => { setApproved(a); setPending(p); setRejected(r); })
      .catch(() => setError('Error al cargar los profesionales'))
      .finally(() => setLoading(false));
  }, []);

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

  const approve = async (id: string) => {
    await api.post(`/professionals/${id}/approve`);
    toast.success('Profesional aprobado');
    load();
  };

  const deny = async (id: string) => {
    await api.post(`/professionals/${id}/deny`);
    toast.success('Solicitud rechazada');
    load();
  };

  const reactivate = async (id: string) => {
    await api.post(`/professionals/${id}/set-pending`);
    toast.success('Movido a revisión');
    load();
  };

  return (
    <div className="space-y-4">
      <h1 className="text-2xl font-bold">Profesionales</h1>
      {error ? (
        <div className="flex flex-col items-center justify-center py-8 text-destructive">
          <p>{error}</p>
          <Button variant="outline" size="sm" onClick={load} className="mt-2">
            Reintentar
          </Button>
        </div>
      ) : (
        <Tabs defaultValue="active">
          <TabsList>
            <TabsTrigger value="active">Activos ({approved.length})</TabsTrigger>
            <TabsTrigger value="pending">Pendientes ({pending.length})</TabsTrigger>
            <TabsTrigger value="rejected">No aprobados ({rejected.length})</TabsTrigger>
          </TabsList>

          <TabsContent value="active">
            <Card>
              <CardContent className="pt-4">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Nombre</TableHead>
                      <TableHead>Profesión</TableHead>
                      <TableHead>Identificación</TableHead>
                      <TableHead>Tarifa</TableHead>
                      <TableHead>Estado</TableHead>
                      <TableHead className="text-right">Acción</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {loading ? (
                      <TableRow><TableCell colSpan={6} className="text-center">Cargando...</TableCell></TableRow>
                    ) : approved.length === 0 ? (
                      <TableRow><TableCell colSpan={6} className="text-center">Sin resultados</TableCell></TableRow>
                    ) : (
                      approved.map((p) => (
                        <TableRow key={p.id}>
                          <TableCell className="font-medium">{p.users?.name}</TableCell>
                          <TableCell>{p.profession || '—'}</TableCell>
                          <TableCell>{p.identification || '—'}</TableCell>
                          <TableCell>{p.rate != null ? `$${p.rate}` : '—'}</TableCell>
                          <TableCell><Badge variant="default">Activo</Badge></TableCell>
                          <TableCell className="text-right">
                            <Link href={`/professionals/${p.id}`}>
                              <Button size="sm" variant="outline">
                                <Eye className="mr-1 h-4 w-4" /> Ver
                              </Button>
                            </Link>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="pending">
            <Card>
              <CardContent className="pt-4">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Nombre</TableHead>
                      <TableHead>Email</TableHead>
                      <TableHead>Teléfono</TableHead>
                      <TableHead>RETHUS</TableHead>
                      <TableHead className="text-right">Acción</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {loading ? (
                      <TableRow><TableCell colSpan={5} className="text-center">Cargando...</TableCell></TableRow>
                    ) : pending.length === 0 ? (
                      <TableRow><TableCell colSpan={5} className="text-center">Sin resultados</TableCell></TableRow>
                    ) : (
                      pending.map((p) => (
                        <TableRow key={p.id}>
                          <TableCell className="font-medium">
                            <Link href={`/professionals/${p.id}`} className="hover:underline text-primary">
                              {p.users?.name}
                            </Link>
                          </TableCell>
                          <TableCell>{p.users?.email || '—'}</TableCell>
                          <TableCell>{p.users?.phone || '—'}</TableCell>
                          <TableCell>
                            {p.rethus_code ? (
                              <div className="flex items-center gap-1">
                                {p.rethus_validated
                                  ? <ShieldCheck className="h-4 w-4 text-green-500" />
                                  : <ShieldAlert className="h-4 w-4 text-yellow-500" />}
                                <span className="font-mono text-xs">{p.rethus_code}</span>
                              </div>
                            ) : (
                              <span className="text-muted-foreground text-xs">No aplica</span>
                            )}
                          </TableCell>
                          <TableCell className="text-right space-x-2">
                            <Link href={`/professionals/${p.id}`}>
                              <Button size="sm" variant="outline">Ver detalle</Button>
                            </Link>
                            <Button size="sm" onClick={() => approve(p.id)}>Aprobar</Button>
                            <Button size="sm" variant="destructive" onClick={() => deny(p.id)}>Rechazar</Button>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          </TabsContent>
          <TabsContent value="rejected">
            <Card>
              <CardContent className="pt-4">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Nombre</TableHead>
                      <TableHead>Email</TableHead>
                      <TableHead>Teléfono</TableHead>
                      <TableHead>RETHUS</TableHead>
                      <TableHead className="text-right">Acción</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {loading ? (
                      <TableRow><TableCell colSpan={5} className="text-center">Cargando...</TableCell></TableRow>
                    ) : rejected.length === 0 ? (
                      <TableRow><TableCell colSpan={5} className="text-center text-muted-foreground">Sin resultados</TableCell></TableRow>
                    ) : (
                      rejected.map((p) => (
                        <TableRow key={p.id}>
                          <TableCell className="font-medium">
                            <Link href={`/professionals/${p.id}`} className="hover:underline text-primary">
                              {p.users?.name}
                            </Link>
                          </TableCell>
                          <TableCell>{p.users?.email || '—'}</TableCell>
                          <TableCell>{p.users?.phone || '—'}</TableCell>
                          <TableCell>
                            {p.rethus_code ? (
                              <div className="flex items-center gap-1">
                                {p.rethus_validated
                                  ? <ShieldCheck className="h-4 w-4 text-green-500" />
                                  : <ShieldAlert className="h-4 w-4 text-yellow-500" />}
                                <span className="font-mono text-xs">{p.rethus_code}</span>
                              </div>
                            ) : (
                              <span className="text-muted-foreground text-xs">No aplica</span>
                            )}
                          </TableCell>
                          <TableCell className="text-right space-x-2">
                            <Link href={`/professionals/${p.id}`}>
                              <Button size="sm" variant="outline">Ver detalle</Button>
                            </Link>
                            <Button size="sm" variant="outline" onClick={() => reactivate(p.id)}>Poner en revisión</Button>
                            <Button size="sm" onClick={() => approve(p.id)}>Aprobar</Button>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      )}
    </div>
  );
}
