import React from 'react';
import { MapPin, Clock, ShieldCheck, History, Fingerprint } from 'lucide-react';
import { motion } from 'framer-motion';
import { Button } from '@/components/ui/button';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { usePonto } from '../../hooks/usePonto';
import { DataTable } from '@/components/shared';
import { TableRow, TableCell } from '@/components/ui/table';

/**
 * Página de Ponto Eletrônico (Template de Referência).
 * Demonstra uso de hooks, animações Framer Motion e geolocalização.
 */
export const PontoPage = () => {
  const { baterPonto, loading, error, location } = usePonto();
  const [historico, setHistorico] = React.useState([
    { id: 1, data: '05/01/2024', entrada: '08:02', saida: '17:10', status: 'Normal' },
    { id: 2, data: '04/01/2024', entrada: '08:15', saida: '17:30', status: 'Atraso' },
  ]);

  const handleBaterPonto = async (tipo) => {
    const result = await baterPonto(tipo);
    if (result.success) {
      // Atualiza histórico local para demonstração
      const now = new Date();
      const novoPonto = {
        id: Date.now(),
        data: now.toLocaleDateString(),
        entrada: now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
        saida: '--:--',
        status: 'Registrado'
      };
      setHistorico([novoPonto, ...historico]);
    }
  };

  return (
    <div className="space-y-8 animate-in fade-in duration-500">
      <div className="flex flex-col gap-2">
        <h2 className="text-3xl font-bold tracking-tight text-slate-900 dark:text-white">Ponto Eletrônico</h2>
        <p className="text-muted-foreground flex items-center gap-2">
          <ShieldCheck className="text-emerald-500" size={18} />
          Registro seguro com geolocalização e criptografia.
        </p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {/* Card Principal de Ação */}
        <Card className="md:col-span-2 overflow-hidden border-none shadow-xl bg-gradient-to-br from-white to-slate-50 dark:from-slate-900 dark:to-slate-950">
          <CardHeader className="border-b bg-white/50 dark:bg-slate-900/50 backdrop-blur-sm">
            <CardTitle className="flex items-center gap-2">
              <Clock className="text-blue-500" size={20} />
              Registro Atual
            </CardTitle>
          </CardHeader>
          <CardContent className="p-8">
            <div className="flex flex-col items-center justify-center space-y-8">
              <motion.div 
                initial={{ scale: 0.9, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                className="text-center"
              >
                <div className="text-5xl font-black tabular-nums tracking-tighter text-slate-800 dark:text-white">
                  {new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
                </div>
                <div className="text-muted-foreground font-medium mt-1">
                  {new Date().toLocaleDateString('pt-BR', { weekday: 'long', day: 'numeric', month: 'long' })}
                </div>
              </motion.div>

              <div className="grid grid-cols-2 gap-4 w-full max-w-sm">
                <Button 
                  size="xl" 
                  className="bg-emerald-600 hover:bg-emerald-700 shadow-lg shadow-emerald-500/20"
                  disabled={loading}
                  onClick={() => handleBaterPonto('entrada')}
                >
                  {loading ? 'Processando...' : 'Entrada'}
                </Button>
                <Button 
                  size="xl" 
                  variant="outline" 
                  className="border-slate-200 dark:border-slate-800"
                  disabled={loading}
                  onClick={() => handleBaterPonto('saida')}
                >
                  Saída
                </Button>
              </div>

              {location && (
                <motion.div 
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="flex items-center gap-2 text-xs font-semibold text-emerald-600 bg-emerald-50 dark:bg-emerald-500/10 px-3 py-1.5 rounded-full"
                >
                  <MapPin size={14} /> Localização capturada com sucesso
                </motion.div>
              )}

              {error && (
                <div className="text-xs text-rose-500 font-medium bg-rose-50 dark:bg-rose-500/10 px-4 py-2 rounded-lg border border-rose-200 dark:border-rose-800 w-full text-center">
                  ⚠️ {error}
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* Card Lateral Informativo */}
        <Card className="shadow-lg border-none bg-indigo-600 text-indigo-50">
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">
              <Fingerprint size={20} />
              Segurança
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <p className="text-sm opacity-90 leading-relaxed">
              Seu registro é autenticado via biometria do dispositivo e validado geograficamente.
            </p>
            <div className="pt-4 border-t border-indigo-500/30">
              <div className="flex items-center justify-between text-xs font-bold uppercase tracking-wider opacity-60">
                IP do Registro
              </div>
              <div className="text-sm font-mono mt-1">177.34.12.89</div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Histórico com DataTable */}
      <div className="space-y-4">
        <h3 className="text-xl font-bold flex items-center gap-2">
          <History size={20} className="text-slate-400" />
          Últimos Registros
        </h3>
        <DataTable 
          columns={['Data', 'Entrada', 'Saída', 'Status']}
          data={historico}
          searchKey="data"
          renderRow={(item) => (
            <TableRow key={item.id} className="group hover:bg-slate-50 dark:hover:bg-slate-900/40 transition-colors">
              <TableCell className="font-semibold">{item.data}</TableCell>
              <TableCell className="text-emerald-600 font-medium">{item.entrada}</TableCell>
              <TableCell className="text-slate-500">{item.saida}</TableCell>
              <TableCell>
                <span className={`px-2 py-0.5 rounded-full text-[10px] font-black uppercase tracking-wider ${
                  item.status === 'Normal' ? 'bg-emerald-100 text-emerald-700' :
                  item.status === 'Atraso' ? 'bg-amber-100 text-amber-700' :
                  'bg-blue-100 text-blue-700'
                }`}>
                  {item.status}
                </span>
              </TableCell>
            </TableRow>
          )}
        />
      </div>
    </div>
  );
};
