import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useToast } from '@/hooks/useToast';
import { useKubeconfigs, KubeconfigItem } from '@/hooks/useKubeconfigs';
import {
  Settings,
  ArrowLeft,
  Plus,
  FileCode,
  MoreVertical,
  Trash2,
  Edit3,
  Copy,
  CheckCircle,
  FolderOpen,
  Upload,
  Download,
  AlertCircle,
  Star,
} from 'lucide-react';

export function KubeconfigSettingsPage() {
  const navigate = useNavigate();
  const { showToast } = useToast();
  const {
    kubeconfigs,
    updateKubeconfig,
    removeKubeconfig,
    setActiveKubeconfig,
    forceReload,
  } = useKubeconfigs();

  const [editModalOpen, setEditModalOpen] = useState(false);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [selectedConfig, setSelectedConfig] = useState<KubeconfigItem | null>(
    null,
  );
  const [newConfigName, setNewConfigName] = useState('');
  const [newConfigPath, setNewConfigPath] = useState('');
  const [newConfigColor, setNewConfigColor] = useState('#3b82f6');

  // Forçar recarregamento quando página carrega
  useEffect(() => {
    forceReload();
  }, []);

  const handleEditConfig = () => {
    if (!selectedConfig || !newConfigName.trim() || !newConfigPath.trim()) {
      showToast({
        title: 'Erro',
        description: 'Nome e caminho são obrigatórios',
        variant: 'destructive',
      });
      return;
    }

    try {
      updateKubeconfig(
        selectedConfig.id,
        newConfigName,
        newConfigPath,
        newConfigColor,
      );
      setEditModalOpen(false);
      setSelectedConfig(null);
      setNewConfigName('');
      setNewConfigPath('');
      setNewConfigColor('#3b82f6');

      showToast({
        title: 'Configuração Atualizada',
        description: 'Kubeconfig foi atualizado com sucesso',
        variant: 'success',
      });
    } catch (error) {
      showToast({
        title: 'Erro',
        description: 'Falha ao atualizar configuração',
        variant: 'destructive',
      });
    }
  };

  const handleDeleteConfig = () => {
    if (!selectedConfig) return;

    try {
      removeKubeconfig(selectedConfig.id);
      setDeleteModalOpen(false);
      setSelectedConfig(null);

      showToast({
        title: 'Configuração Removida',
        description: 'Kubeconfig foi removido com sucesso',
        variant: 'success',
      });
    } catch (error) {
      showToast({
        title: 'Erro',
        description:
          error instanceof Error
            ? error.message
            : 'Falha ao remover configuração',
        variant: 'destructive',
      });
    }
  };

  const handleSetActive = (config: KubeconfigItem) => {
    setActiveKubeconfig(config.id);

    showToast({
      title: 'Configuração Ativa',
      description: `"${config.name}" é agora a configuração ativa`,
      variant: 'success',
    });
  };

  const openEditModal = (config: KubeconfigItem) => {
    setSelectedConfig(config);
    setNewConfigName(config.name);
    setNewConfigPath(config.path);
    setNewConfigColor(config.color || '#3b82f6');
    setEditModalOpen(true);
  };

  const openDeleteModal = (config: KubeconfigItem) => {
    setSelectedConfig(config);
    setDeleteModalOpen(true);
  };

  const copyPath = (path: string) => {
    navigator.clipboard.writeText(path);
    showToast({
      title: 'Copiado',
      description: 'Caminho copiado para a área de transferência',
      variant: 'success',
    });
  };

  const formatDate = (isoString: string) => {
    try {
      const date = new Date(isoString);
      return date.toLocaleDateString('pt-BR');
    } catch {
      return 'Data inválida';
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button variant="ghost" size="icon" onClick={() => navigate(-1)}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold text-foreground flex items-center">
              <Settings className="h-8 w-8 mr-3 text-blue-600" />
              Gerenciar Configurações
            </h1>
            <p className="text-muted-foreground">
              Configure e gerencie arquivos kubeconfig para conectar a
              diferentes clusters
            </p>
          </div>
        </div>
        <Button onClick={() => navigate('/settings/kubeconfigs/add')}>
          <Plus className="h-4 w-4 mr-2" />
          Adicionar Configuração
        </Button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 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>
            <FileCode className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{kubeconfigs.length}</div>
            <p className="text-xs text-muted-foreground">
              Configurações disponíveis
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Ativa</CardTitle>
            <CheckCircle className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">1</div>
            <p className="text-xs text-muted-foreground">Configuração em uso</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Padrão</CardTitle>
            <Star className="h-4 w-4 text-orange-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-600">1</div>
            <p className="text-xs text-muted-foreground">Configuração padrão</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              Personalizadas
            </CardTitle>
            <Plus className="h-4 w-4 text-purple-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-purple-600">
              {kubeconfigs.filter((c) => !c.isDefault).length}
            </div>
            <p className="text-xs text-muted-foreground">
              Adicionadas pelo usuário
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Configurations Table */}
      <Card>
        <CardHeader>
          <CardTitle>Configurações de Kubeconfig</CardTitle>
          <CardDescription>
            Gerencie suas configurações de acesso aos clusters Kubernetes
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Nome</TableHead>
                <TableHead>Caminho</TableHead>
                <TableHead>Cor</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Criado em</TableHead>
                <TableHead className="w-16">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {kubeconfigs.map((config) => (
                <TableRow key={config.id}>
                  <TableCell>
                    <div className="flex items-center space-x-2">
                      <div
                        className="w-4 h-4 rounded-full border-2 border-gray-200"
                        style={{ backgroundColor: config.color || '#3b82f6' }}
                      />
                      <span className="font-medium">{config.name}</span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center space-x-2">
                      <code className="text-sm font-mono bg-muted px-2 py-1 rounded">
                        {config.path}
                      </code>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-6 w-6"
                        onClick={() => copyPath(config.path)}
                      >
                        <Copy className="h-3 w-3" />
                      </Button>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex justify-center">
                      <div
                        className="w-6 h-6 rounded-full border-2 border-gray-200 shadow-sm"
                        style={{ backgroundColor: config.color || '#3b82f6' }}
                      />
                    </div>
                  </TableCell>
                  <TableCell>
                    {config.isActive ? (
                      <Badge className="bg-green-100 text-green-800">
                        <CheckCircle className="h-3 w-3 mr-1" />
                        Ativo
                      </Badge>
                    ) : (
                      <Badge variant="outline">Inativo</Badge>
                    )}
                  </TableCell>
                  <TableCell>
                    <span className="text-sm text-muted-foreground">
                      {formatDate(config.createdAt)}
                    </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>
                        {!config.isActive && (
                          <>
                            <DropdownMenuItem
                              onClick={() => handleSetActive(config)}
                            >
                              <CheckCircle className="h-4 w-4 mr-2" />
                              Ativar
                            </DropdownMenuItem>
                            <DropdownMenuSeparator />
                          </>
                        )}
                        <DropdownMenuItem onClick={() => openEditModal(config)}>
                          <Edit3 className="h-4 w-4 mr-2" />
                          Editar
                        </DropdownMenuItem>
                        {!config.isDefault && (
                          <>
                            <DropdownMenuSeparator />
                            <DropdownMenuItem
                              onClick={() => openDeleteModal(config)}
                              className="text-red-600"
                            >
                              <Trash2 className="h-4 w-4 mr-2" />
                              Remover
                            </DropdownMenuItem>
                          </>
                        )}
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Edit Configuration Modal */}
      <Dialog open={editModalOpen} onOpenChange={setEditModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Editar Configuração</DialogTitle>
            <DialogDescription>
              Modifique o nome e caminho da configuração selecionada.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label htmlFor="editConfigName">Nome da Configuração</Label>
              <Input
                id="editConfigName"
                value={newConfigName}
                onChange={(e) => setNewConfigName(e.target.value)}
              />
            </div>
            <div>
              <Label htmlFor="editConfigPath">Caminho do Arquivo</Label>
              <Input
                id="editConfigPath"
                value={newConfigPath}
                onChange={(e) => setNewConfigPath(e.target.value)}
              />
            </div>
            <div>
              <Label htmlFor="editConfigColor">Cor do Ambiente</Label>
              <div className="flex items-center space-x-3 mt-2">
                <input
                  id="editConfigColor"
                  type="color"
                  value={newConfigColor}
                  onChange={(e) => setNewConfigColor(e.target.value)}
                  className="w-12 h-10 rounded-md border border-input cursor-pointer"
                />
                <div className="flex-1">
                  <Input
                    value={newConfigColor}
                    onChange={(e) => setNewConfigColor(e.target.value)}
                    placeholder="#3b82f6"
                  />
                </div>
              </div>
              <p className="text-sm text-muted-foreground mt-1">
                Esta cor será aplicada ao menu lateral quando a configuração
                estiver ativa
              </p>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditModalOpen(false)}>
              Cancelar
            </Button>
            <Button onClick={handleEditConfig}>Salvar</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Configuration Modal */}
      <Dialog open={deleteModalOpen} onOpenChange={setDeleteModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Remover Configuração</DialogTitle>
            <DialogDescription>
              Tem certeza que deseja remover a configuração{' '}
              <strong>{selectedConfig?.name}</strong>?
              <br />
              <br />
              Esta ação não pode ser desfeita.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteModalOpen(false)}>
              Cancelar
            </Button>
            <Button variant="destructive" onClick={handleDeleteConfig}>
              <Trash2 className="h-4 w-4 mr-2" />
              Remover
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
