import React, { useState, useMemo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  useConfigMapsInfo,
  useKubectl,
  ConfigMapInfo,
} from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  Loader2,
  Map,
  AlertCircle,
  RefreshCw,
  Filter,
  MoreVertical,
  Trash2,
  ArrowUpDown,
  Eye,
  FileText,
  Pause,
  Play,
  Key,
  Settings,
  XCircle,
  ChevronDown,
  Plus,
  Upload,
} from 'lucide-react';

function ConfigMapsPage() {
  const navigate = useNavigate();
  const { configMaps, namespaces, loading, error, refetch, backgroundRefetch } =
    useConfigMapsInfo();
  const { executeCommand } = useKubectl();
  const { showToast } = useToast();
  const { selectedNamespace, setSelectedNamespace } = useGlobalNamespace();

  const [sortField, setSortField] = useState<string>('name');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
  const [searchQuery, setSearchQuery] = useState('');
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [configMapRefreshInterval, setConfigMapRefreshInterval] =
    useState(30000); // 30 segundos

  // Modal states
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [selectedConfigMap, setSelectedConfigMap] =
    useState<ConfigMapInfo | null>(null);
  const [deleting, setDeleting] = useState(false);

  // Auto-refresh effect
  useEffect(() => {
    if (!autoRefresh) return undefined;

    const interval = setInterval(() => {
      backgroundRefetch();
    }, configMapRefreshInterval);

    return () => clearInterval(interval);
  }, [autoRefresh, configMapRefreshInterval, backgroundRefetch]);

  // Filter and sort configmaps
  const filteredAndSortedConfigMaps = useMemo(() => {
    let filtered = configMaps;

    // Filter by namespace
    if (selectedNamespace !== 'all') {
      filtered = filtered.filter((cm) => cm.namespace === selectedNamespace);
    }

    // Filter by search query
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (cm) =>
          cm.name.toLowerCase().includes(query) ||
          cm.namespace.toLowerCase().includes(query) ||
          Object.keys(cm.data).some((key) => key.toLowerCase().includes(query)),
      );
    }

    // Sort
    return filtered.sort((a, b) => {
      let aValue: any;
      let bValue: any;

      switch (sortField) {
        case 'name':
          aValue = a.name;
          bValue = b.name;
          break;
        case 'namespace':
          aValue = a.namespace;
          bValue = b.namespace;
          break;
        case 'dataCount':
          aValue = a.dataCount;
          bValue = b.dataCount;
          break;
        case 'age':
          aValue = new Date(a.creationTimestamp).getTime();
          bValue = new Date(b.creationTimestamp).getTime();
          break;
        default:
          aValue = a.name;
          bValue = b.name;
      }

      if (sortDirection === 'asc') {
        if (aValue < bValue) return -1;
        if (aValue > bValue) return 1;
        return 0;
      }
      if (aValue > bValue) return -1;
      if (aValue < bValue) return 1;
      return 0;
    });
  }, [configMaps, selectedNamespace, searchQuery, sortField, sortDirection]);

  const handleSort = (field: string) => {
    if (sortField === field) {
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortDirection('asc');
    }
  };

  const getAge = (creationTimestamp: string) => {
    const now = new Date();
    const created = new Date(creationTimestamp);
    const diffMs = now.getTime() - created.getTime();
    const diffSeconds = Math.floor(diffMs / 1000);
    const diffMinutes = Math.floor(diffSeconds / 60);
    const diffHours = Math.floor(diffMinutes / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffDays > 0) return `${diffDays}d`;
    if (diffHours > 0) return `${diffHours}h`;
    if (diffMinutes > 0) return `${diffMinutes}m`;
    return `${diffSeconds}s`;
  };

  const handleDeleteConfigMap = async () => {
    if (!selectedConfigMap) return;

    setDeleting(true);
    try {
      const command = `kubectl delete configmap ${selectedConfigMap.name} -n ${selectedConfigMap.namespace}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'ConfigMap Excluído',
          description: `ConfigMap "${selectedConfigMap.name}" foi excluído com sucesso`,
          variant: 'success',
        });

        backgroundRefetch();
      } else {
        showToast({
          title: 'Erro ao Excluir ConfigMap',
          description: result.error || 'Falha ao excluir o ConfigMap',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setDeleting(false);
      setDeleteModalOpen(false);
      setSelectedConfigMap(null);
    }
  };

  const handleDeleteClick = (configMap: ConfigMapInfo) => {
    setSelectedConfigMap(configMap);
    setDeleteModalOpen(true);
  };

  const statusStats = useMemo(() => {
    const filtered =
      selectedNamespace === 'all'
        ? configMaps
        : configMaps.filter((cm) => cm.namespace === selectedNamespace);

    return {
      total: filtered.length,
      withData: filtered.filter((cm) => cm.dataCount > 0).length,
      empty: filtered.filter((cm) => cm.dataCount === 0).length,
      totalKeys: filtered.reduce((sum, cm) => sum + cm.dataCount, 0),
      avgKeys:
        filtered.length > 0
          ? Math.round(
              filtered.reduce((sum, cm) => sum + cm.dataCount, 0) /
                filtered.length,
            )
          : 0,
    };
  }, [configMaps, selectedNamespace]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
          <p className="text-muted-foreground">Carregando ConfigMaps...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <AlertCircle className="h-8 w-8 text-red-500 mx-auto mb-4" />
          <p className="text-red-600 mb-4">{error}</p>
          <Button onClick={() => refetch()}>
            <RefreshCw className="h-4 w-4 mr-2" />
            Tentar Novamente
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground flex items-center">
            <Map className="h-8 w-8 mr-3 text-blue-600" />
            ConfigMaps
          </h1>
          <p className="text-muted-foreground">
            Gerencie e monitore todos os ConfigMaps do cluster
          </p>
        </div>
        <div className="flex items-center space-x-2">
          {/* Split button - Live/Manual com dropdown de tempo */}
          <div className="flex">
            {/* Botão principal - Play/Pause */}
            <Button
              onClick={() => setAutoRefresh(!autoRefresh)}
              variant="ghost"
              className="rounded-r-none border-r-0 text-muted-foreground hover:text-foreground hover:bg-muted/50"
              title={
                autoRefresh
                  ? 'Pausar atualização automática'
                  : 'Ativar atualização automática'
              }
            >
              {autoRefresh ? (
                <>
                  <Pause className="h-4 w-4 mr-2" />
                  Live ({configMapRefreshInterval / 1000}s)
                </>
              ) : (
                <>
                  <Play className="h-4 w-4 mr-2" />
                  Atualizar
                </>
              )}
            </Button>

            {/* Dropdown de tempo */}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  className="rounded-l-none px-2 h-10 text-muted-foreground hover:text-foreground hover:bg-muted/50"
                  title="Configurar intervalo de refresh"
                >
                  <ChevronDown className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuLabel>Intervalo de Refresh</DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem
                  onClick={() => setConfigMapRefreshInterval(1000)}
                  className={
                    configMapRefreshInterval === 1000 ? 'bg-green-100' : ''
                  }
                >
                  1 segundo
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setConfigMapRefreshInterval(3000)}
                  className={
                    configMapRefreshInterval === 3000 ? 'bg-green-100' : ''
                  }
                >
                  3 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setConfigMapRefreshInterval(5000)}
                  className={
                    configMapRefreshInterval === 5000 ? 'bg-green-100' : ''
                  }
                >
                  5 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setConfigMapRefreshInterval(7000)}
                  className={
                    configMapRefreshInterval === 7000 ? 'bg-green-100' : ''
                  }
                >
                  7 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setConfigMapRefreshInterval(10000)}
                  className={
                    configMapRefreshInterval === 10000 ? 'bg-green-100' : ''
                  }
                >
                  10 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setConfigMapRefreshInterval(30000)}
                  className={
                    configMapRefreshInterval === 30000 ? 'bg-green-100' : ''
                  }
                >
                  30 segundos
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>

          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline">
                <MoreVertical className="h-4 w-4 mr-2" />
                Ações
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuLabel>Ações de ConfigMap</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem
                onClick={() => navigate('/storage/configmaps/new')}
              >
                <Plus className="h-4 w-4 mr-2" />
                Novo
              </DropdownMenuItem>
              <DropdownMenuItem
                onClick={() => navigate('/storage/configmaps/import')}
              >
                <Upload className="h-4 w-4 mr-2" />
                Importar
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total</CardTitle>
            <Map className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{statusStats.total}</div>
            <p className="text-xs text-muted-foreground">
              ConfigMaps no cluster
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">With Data</CardTitle>
            <FileText className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {statusStats.withData}
            </div>
            <p className="text-xs text-muted-foreground">Com configurações</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Empty</CardTitle>
            <XCircle className="h-4 w-4 text-gray-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-gray-600">
              {statusStats.empty}
            </div>
            <p className="text-xs text-muted-foreground">Vazios</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Keys</CardTitle>
            <Key className="h-4 w-4 text-orange-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-600">
              {statusStats.totalKeys}
            </div>
            <p className="text-xs text-muted-foreground">Chaves configuradas</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Avg Keys</CardTitle>
            <Settings className="h-4 w-4 text-purple-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-purple-600">
              {statusStats.avgKeys}
            </div>
            <p className="text-xs text-muted-foreground">Média por ConfigMap</p>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Filter className="h-5 w-5 mr-2" />
            Filtros
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap gap-4">
            <div className="flex-1 min-w-[200px]">
              <Label className="text-sm font-medium mb-2 block">
                Namespace
              </Label>
              <Select
                value={selectedNamespace}
                onValueChange={setSelectedNamespace}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Selecione um namespace" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos os namespaces</SelectItem>
                  {namespaces.map((ns) => (
                    <SelectItem key={ns} value={ns}>
                      {ns}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="flex-1 min-w-[200px]">
              <Label className="text-sm font-medium mb-2 block">Buscar</Label>
              <input
                type="text"
                placeholder="Nome, namespace, chave..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* ConfigMaps Table */}
      <Card>
        <CardHeader>
          <CardTitle>
            {filteredAndSortedConfigMaps.length} ConfigMap(s) encontrado(s)
            {selectedNamespace !== 'all' && ` em ${selectedNamespace}`}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('name')}
                  >
                    Nome
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('namespace')}
                  >
                    Namespace
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('dataCount')}
                  >
                    Data Keys
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('age')}
                  >
                    Idade
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead className="w-16">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredAndSortedConfigMaps.map((configMap) => {
                return (
                  <TableRow key={`${configMap.namespace}-${configMap.name}`}>
                    <TableCell>
                      <button
                        type="button"
                        className="text-blue-600 hover:text-blue-800 hover:underline text-left font-medium"
                        onClick={() =>
                          navigate(
                            `/storage/configmaps/${configMap.namespace}/${configMap.name}`,
                          )
                        }
                      >
                        {configMap.name}
                      </button>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{configMap.namespace}</Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary">{configMap.dataCount}</Badge>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-muted-foreground">
                        {getAge(configMap.creationTimestamp)}
                      </span>
                    </TableCell>
                    <TableCell>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8"
                          >
                            <MoreVertical className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuLabel>Ações</DropdownMenuLabel>
                          <DropdownMenuItem
                            onClick={() =>
                              navigate(
                                `/storage/configmaps/${configMap.namespace}/${configMap.name}`,
                              )
                            }
                          >
                            <Eye className="h-4 w-4 mr-2" />
                            Visualizar
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            onClick={() => handleDeleteClick(configMap)}
                            className="text-red-600"
                          >
                            <Trash2 className="h-4 w-4 mr-2" />
                            Excluir
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                );
              })}
              {filteredAndSortedConfigMaps.length === 0 && (
                <TableRow>
                  <TableCell colSpan={5} className="text-center py-8">
                    <div className="text-muted-foreground">
                      <Map className="h-8 w-8 mx-auto mb-2 opacity-50" />
                      <p>Nenhum ConfigMap encontrado</p>
                      {(searchQuery || selectedNamespace !== 'all') && (
                        <p className="text-sm mt-1">
                          Tente ajustar os filtros para ver mais resultados
                        </p>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Delete Confirmation Modal */}
      <Dialog open={deleteModalOpen} onOpenChange={setDeleteModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Excluir ConfigMap</DialogTitle>
            <DialogDescription>
              Tem certeza que deseja excluir o ConfigMap{' '}
              <strong>{selectedConfigMap?.name}</strong> do namespace{' '}
              <strong>{selectedConfigMap?.namespace}</strong>?
              <br />
              <br />
              Esta ação não pode ser desfeita e pode afetar pods que dependem
              dessas configurações.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setDeleteModalOpen(false)}
              disabled={deleting}
            >
              Cancelar
            </Button>
            <Button
              variant="destructive"
              onClick={handleDeleteConfigMap}
              disabled={deleting}
            >
              {deleting ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Excluindo...
                </>
              ) : (
                <>
                  <Trash2 className="h-4 w-4 mr-2" />
                  Excluir ConfigMap
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

export default ConfigMapsPage;
