﻿import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
    Calendar, ArrowLeft, Search, CheckCircle, XCircle, Edit,
    Trash2, ClipboardList
} from "lucide-react";
import { useNavigate } from "react-router-dom";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "sonner";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";

interface HistoriqueAction {
    Id: number;
    collaborateur: string;
    realisePar: string;
    Action: string;
    Details: string;
    DateAction: string;
    AdresseIP: string;
    DemandeCongeId: number;
}

const Historique = () => {
    const navigate = useNavigate();
    const [historique, setHistorique] = useState<HistoriqueAction[]>([]);
    const [recherche, setRecherche] = useState("");
    const [filtreAction, setFiltreAction] = useState("all");
    const [dateDebut, setDateDebut] = useState("");
    const [dateFin, setDateFin] = useState("");
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        chargerHistorique();
    }, [filtreAction, dateDebut, dateFin]);

    const chargerHistorique = async () => {
        setLoading(true);
        try {
            const token = localStorage.getItem('token');
            const params = new URLSearchParams();

            if (dateDebut) params.append('dateDebut', dateDebut);
            if (dateFin) params.append('dateFin', dateFin);
            if (filtreAction !== 'all') params.append('action', filtreAction);

            const response = await fetch(
                `/api/historique?${params.toString()}`,
                { headers: { 'Authorization': `Bearer ${token}` } }
            );

            // ⭐ VÉRIFICATION
            if (!response.ok) {
                throw new Error(`Erreur ${response.status}`);
            }

            const data = await response.json();

            // ⭐ SÉCURITÉ : Vérifier que c'est un tableau
            if (Array.isArray(data)) {
                setHistorique(data);
            } else {
                console.error('❌ Format historique invalide:', data);
                setHistorique([]);
            }
        } catch (error) {
            console.error('❌ Erreur chargement historique:', error);
            toast.error("Erreur lors du chargement de l'historique");
            setHistorique([]); // ⭐ Toujours mettre un tableau vide en cas d'erreur
        } finally {
            setLoading(false);
        }
    };

    // ⭐ SÉCURITÉ : Vérifier que historique est un tableau avant filter
    const historiqueFiltré = Array.isArray(historique)
        ? historique.filter(h => {
            const matchRecherche = h.collaborateur?.toLowerCase().includes(recherche.toLowerCase()) ||
                h.realisePar?.toLowerCase().includes(recherche.toLowerCase()) ||
                h.Details?.toLowerCase().includes(recherche.toLowerCase());
            return matchRecherche;
        })
        : [];

    const getActionIcon = (action: string) => {
        if (action.includes('Validation')) return <CheckCircle className="w-4 h-4 text-success" />;
        if (action.includes('Refus')) return <XCircle className="w-4 h-4 text-destructive" />;
        if (action.includes('Modification')) return <Edit className="w-4 h-4 text-warning" />;
        if (action.includes('Suppression')) return <Trash2 className="w-4 h-4 text-destructive" />;
        return <ClipboardList className="w-4 h-4 text-primary" />;
    };

    const getActionBadge = (action: string) => {
        if (action.includes('Validation')) {
            return <Badge variant="outline" className="bg-success/10 text-success border-success/20">
                {action}
            </Badge>;
        }
        if (action.includes('Refus')) {
            return <Badge variant="outline" className="bg-destructive/10 text-destructive border-destructive/20">
                {action}
            </Badge>;
        }
        if (action.includes('Modification')) {
            return <Badge variant="outline" className="bg-warning/10 text-warning border-warning/20">
                {action}
            </Badge>;
        }
        return <Badge variant="secondary">{action}</Badge>;
    };

    const formatDateTime = (dateString: string) => {
        return new Date(dateString).toLocaleString('fr-FR', {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    const exporterHistorique = () => {
        if (historiqueFiltré.length === 0) {
            toast.error("Aucune donnée à exporter");
            return;
        }

        const headers = ['Date et heure', 'Collaborateur concerné', 'Action réalisée par', 'Action', 'Détails', 'Demande ID'];
        const csvContent = [
            headers.join(';'),
            ...historiqueFiltré.map(row => [
                formatDateTime(row.DateAction),
                row.collaborateur,
                row.realisePar,
                row.Action,
                row.Details,
                row.DemandeCongeId || ''
            ].join(';'))
        ].join('\n');

        const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `historique_actions_${new Date().toISOString().split('T')[0]}.csv`;
        link.click();
        toast.success("Export réussi");
    };

    return (
        <div className="min-h-screen bg-gradient-subtle">
            <header className="bg-card border-b border-border shadow-card">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
                    <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-4">
                            <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => navigate("/dashboard")}
                                className="transition-smooth"
                            >
                                <ArrowLeft className="w-4 h-4 mr-2" />
                                Retour
                            </Button>
                            <div className="flex items-center space-x-3">
                                <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ backgroundColor: "#7e5aa2" }}>
                                    <ClipboardList className="w-5 h-5 text-primary-foreground" />
                                </div>
                                <h1 className="text-2xl font-bold text-foreground">Historique des actions</h1>
                            </div>
                        </div>
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={exporterHistorique}
                            disabled={historiqueFiltré.length === 0}
                        >
                            Exporter CSV
                        </Button>
                    </div>
                </div>
            </header>

            <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                <Card className="shadow-card border-0 mb-8">
                    <CardContent className="p-6">
                        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                            <div className="relative">
                                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                                <Input
                                    placeholder="Rechercher..."
                                    value={recherche}
                                    onChange={(e) => setRecherche(e.target.value)}
                                    className="pl-10"
                                />
                            </div>

                            <Select value={filtreAction} onValueChange={setFiltreAction}>
                                <SelectTrigger>
                                    <SelectValue placeholder="Type d'action" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">Toutes les actions</SelectItem>
                                    <SelectItem value="Validation congé">Validations</SelectItem>
                                    <SelectItem value="Refus congé">Refus</SelectItem>
                                    <SelectItem value="Création demande">Créations</SelectItem>
                                    <SelectItem value="Modification demande">Modifications</SelectItem>
                                    <SelectItem value="Suppression demande">Suppressions</SelectItem>
                                </SelectContent>
                            </Select>

                            <Input
                                type="date"
                                value={dateDebut}
                                onChange={(e) => setDateDebut(e.target.value)}
                                placeholder="Date début"
                            />

                            <Input
                                type="date"
                                value={dateFin}
                                onChange={(e) => setDateFin(e.target.value)}
                                placeholder="Date fin"
                            />
                        </div>
                    </CardContent>
                </Card>

                <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
                    <Card className="shadow-card border-0">
                        <CardContent className="p-6">
                            <div className="flex items-center justify-between">
                                <div>
                                    <p className="text-sm text-muted-foreground">Total actions</p>
                                    <p className="text-2xl font-bold">{historiqueFiltré.length}</p>
                                </div>
                                <ClipboardList className="w-8 h-8 text-primary" />
                            </div>
                        </CardContent>
                    </Card>

                    <Card className="shadow-card border-0">
                        <CardContent className="p-6">
                            <div className="flex items-center justify-between">
                                <div>
                                    <p className="text-sm text-muted-foreground">Validations</p>
                                    <p className="text-2xl font-bold text-success">
                                        {historique.filter(h => h.Action.includes('Validation')).length}
                                    </p>
                                </div>
                                <CheckCircle className="w-8 h-8 text-success" />
                            </div>
                        </CardContent>
                    </Card>

                    <Card className="shadow-card border-0">
                        <CardContent className="p-6">
                            <div className="flex items-center justify-between">
                                <div>
                                    <p className="text-sm text-muted-foreground">Refus</p>
                                    <p className="text-2xl font-bold text-destructive">
                                        {historique.filter(h => h.Action.includes('Refus')).length}
                                    </p>
                                </div>
                                <XCircle className="w-8 h-8 text-destructive" />
                            </div>
                        </CardContent>
                    </Card>

                    <Card className="shadow-card border-0">
                        <CardContent className="p-6">
                            <div className="flex items-center justify-between">
                                <div>
                                    <p className="text-sm text-muted-foreground">Modifications</p>
                                    <p className="text-2xl font-bold text-warning">
                                        {historique.filter(h => h.Action.includes('Modification')).length}
                                    </p>
                                </div>
                                <Edit className="w-8 h-8 text-warning" />
                            </div>
                        </CardContent>
                    </Card>
                </div>

                <Card className="shadow-card border-0">
                    <CardHeader>
                        <CardTitle>Journal des actions</CardTitle>
                        <CardDescription>
                            Traçabilité complète de toutes les actions effectuées
                        </CardDescription>
                    </CardHeader>
                    <CardContent>
                        {loading ? (
                            <div className="text-center py-12">
                                <div className="w-16 h-16 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4" />
                                <p className="text-muted-foreground">Chargement...</p>
                            </div>
                        ) : historiqueFiltré.length > 0 ? (
                            <div className="overflow-x-auto">
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>Date et heure</TableHead>
                                            <TableHead>Collaborateur concerné</TableHead>
                                            <TableHead>Action réalisée par</TableHead>
                                            <TableHead>Action</TableHead>
                                            <TableHead>Détails</TableHead>
                                            <TableHead className="text-center">Demande</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {historiqueFiltré.map((action) => (
                                            <TableRow key={action.Id}>
                                                <TableCell className="font-medium">
                                                    {formatDateTime(action.DateAction)}
                                                </TableCell>
                                                <TableCell>{action.collaborateur}</TableCell>
                                                <TableCell>
                                                    <span className="text-muted-foreground">
                                                        {action.realisePar || '-'}
                                                    </span>
                                                </TableCell>
                                                <TableCell>
                                                    <div className="flex items-center gap-2">
                                                        {getActionIcon(action.Action)}
                                                        {getActionBadge(action.Action)}
                                                    </div>
                                                </TableCell>
                                                <TableCell className="max-w-md">
                                                    <p className="text-sm text-muted-foreground truncate">
                                                        {action.Details}
                                                    </p>
                                                </TableCell>
                                                <TableCell className="text-center">
                                                    {action.DemandeCongeId ? (
                                                        <Button
                                                            variant="ghost"
                                                            size="sm"
                                                            onClick={() => navigate(`/demandes/${action.DemandeCongeId}`)}
                                                        >
                                                            #{action.DemandeCongeId}
                                                        </Button>
                                                    ) : (
                                                        <span className="text-muted-foreground">-</span>
                                                    )}
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            </div>
                        ) : (
                            <div className="text-center py-12">
                                <ClipboardList className="w-16 h-16 text-muted-foreground mx-auto mb-4 opacity-50" />
                                <p className="text-muted-foreground text-lg">Aucune action trouvée</p>
                            </div>
                        )}
                    </CardContent>
                </Card>
            </main>
        </div>
    );
};

export default Historique;