import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useToast } from '@/hooks/useToast';
import { useKubectl, useNamespacesInfo } from '@/hooks/useKubectl';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  ArrowLeft,
  Settings,
  Plus,
  Trash2,
  CheckCircle,
  Loader2,
  Tag,
  Database,
} from 'lucide-react';

interface ServicePort {
  id: string;
  name: string;
  port: number;
  targetPort: number;
  protocol: 'TCP' | 'UDP';
}

export function ServiceCreateHeadlessPage() {
  const navigate = useNavigate();
  const { showToast } = useToast();
  const { executeCommand } = useKubectl();
  const { namespaces } = useNamespacesInfo();
  const { selectedNamespace: globalNamespace } = useGlobalNamespace();

  const [serviceName, setServiceName] = useState('');
  const [selectedNamespace, setSelectedNamespace] = useState(() => {
    return globalNamespace === 'all' ? 'default' : globalNamespace;
  });
  const [selector, setSelector] = useState('app');
  const [selectorValue, setSelectorValue] = useState('');
  const [ports, setPorts] = useState<ServicePort[]>([
    {
      id: '1',
      name: 'http',
      port: 80,
      targetPort: 8080,
      protocol: 'TCP',
    },
  ]);
  const [creating, setCreating] = useState(false);

  const addPort = () => {
    const newPort: ServicePort = {
      id: Date.now().toString(),
      name: '',
      port: 80,
      targetPort: 8080,
      protocol: 'TCP',
    };
    setPorts([...ports, newPort]);
  };

  const removePort = (portId: string) => {
    if (ports.length > 1) {
      setPorts(ports.filter((port) => port.id !== portId));
    }
  };

  const updatePort = (portId: string, updates: Partial<ServicePort>) => {
    setPorts(ports.map((port) => 
      port.id === portId ? { ...port, ...updates } : port
    ));
  };

  const validateForm = () => {
    if (!serviceName.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Nome do Service é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    if (!selectedNamespace) {
      showToast({
        title: 'Erro de Validação',
        description: 'Namespace é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    if (!selectorValue.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Valor do selector é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    // Validate ports
    for (const port of ports) {
      if (!port.port || port.port <= 0 || port.port > 65535) {
        showToast({
          title: 'Erro de Validação',
          description: 'Porta deve estar entre 1 e 65535',
          variant: 'destructive',
        });
        return false;
      }

      if (!port.targetPort || port.targetPort <= 0 || port.targetPort > 65535) {
        showToast({
          title: 'Erro de Validação',
          description: 'Target Port deve estar entre 1 e 65535',
          variant: 'destructive',
        });
        return false;
      }
    }

    return true;
  };

  const handleCreateService = async () => {
    if (!validateForm()) return;

    setCreating(true);
    try {
      // Build ports section
      const portsYaml = ports.map((port) => `
  - name: ${port.name || `port-${port.port}`}
    port: ${port.port}
    targetPort: ${port.targetPort}
    protocol: ${port.protocol}`).join('');

      const serviceYaml = `apiVersion: v1
kind: Service
metadata:
  name: ${serviceName}
  namespace: ${selectedNamespace}
spec:
  clusterIP: None
  selector:
    ${selector}: ${selectorValue}
  ports:${portsYaml}`;

      // Create temporary file with the service spec
      const tempFileName = `/tmp/service-headless-${serviceName}-${Date.now()}.yaml`;
      const writeCommand = `cat > "${tempFileName}" << 'EOF'
${serviceYaml}
EOF`;

      const writeResult = await executeCommand(writeCommand);
      if (!writeResult.success) {
        throw new Error('Falha ao criar arquivo temporário');
      }

      // Apply the service
      const applyCommand = `kubectl apply -f "${tempFileName}"`;
      const result = await executeCommand(applyCommand);

      // Clean up temp file
      await executeCommand(`rm -f "${tempFileName}"`);

      if (result.success) {
        showToast({
          title: 'Service Headless Criado com Sucesso',
          description: `Service "${serviceName}" foi criado no namespace "${selectedNamespace}"`,
          variant: 'success',
        });
        navigate('/service-discovery/services');
      } else {
        showToast({
          title: 'Erro ao Criar Service',
          description: result.error || 'Falha ao criar o Service',
          variant: 'destructive',
        });
      }
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setCreating(false);
    }
  };

  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-gray-600" />
              Criar Service Headless
            </h1>
            <p className="text-muted-foreground">
              Configure um Service sem IP próprio para descoberta direta de pods
            </p>
          </div>
        </div>
      </div>

      {/* Basic Info */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Settings className="h-5 w-5 mr-2" />
            Informações Básicas
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="serviceName">Nome do Service</Label>
              <Input
                id="serviceName"
                placeholder="ex: my-statefulset-headless"
                value={serviceName}
                onChange={(e) => setServiceName(e.target.value)}
              />
            </div>
            <div>
              <Label htmlFor="namespace">Namespace</Label>
              <Select
                value={selectedNamespace}
                onValueChange={setSelectedNamespace}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Selecione o namespace" />
                </SelectTrigger>
                <SelectContent>
                  {namespaces.map((ns) => (
                    <SelectItem key={ns.name} value={ns.name}>
                      {ns.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Pod Selector */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Tag className="h-5 w-5 mr-2" />
            Seletor de Pods
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="selector">Chave do Selector</Label>
              <Select
                value={selector}
                onValueChange={setSelector}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="app">app</SelectItem>
                  <SelectItem value="name">name</SelectItem>
                  <SelectItem value="component">component</SelectItem>
                  <SelectItem value="service">service</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="selectorValue">Valor do Selector</Label>
              <Input
                id="selectorValue"
                placeholder="ex: my-statefulset"
                value={selectorValue}
                onChange={(e) => setSelectorValue(e.target.value)}
              />
            </div>
          </div>
          <div className="p-3 bg-gray-50 rounded-md border border-gray-200">
            <p className="text-sm text-gray-700">
              <strong>Selector:</strong> {selector}={selectorValue || '<valor>'}
            </p>
            <p className="text-xs text-gray-600 mt-1">
              <strong>ClusterIP:</strong> None (Headless) - DNS retornará IPs dos pods diretamente
            </p>
          </div>
        </CardContent>
      </Card>

      {/* Ports Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <Database className="h-5 w-5 mr-2" />
              Configuração de Portas
            </div>
            <Button onClick={addPort} size="sm">
              <Plus className="h-4 w-4 mr-2" />
              Adicionar Porta
            </Button>
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {ports.map((port, index) => (
            <Card key={port.id} className="border-gray-200">
              <CardHeader className="pb-3">
                <div className="flex items-center justify-between">
                  <h4 className="font-medium">Porta {index + 1}</h4>
                  {ports.length > 1 && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => removePort(port.id)}
                      className="text-red-600 hover:text-red-800"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  )}
                </div>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                  <div>
                    <Label>Nome da Porta</Label>
                    <Input
                      placeholder="ex: http"
                      value={port.name}
                      onChange={(e) => updatePort(port.id, { name: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label>Porta do Service</Label>
                    <Input
                      type="number"
                      placeholder="80"
                      value={port.port}
                      onChange={(e) => updatePort(port.id, { port: parseInt(e.target.value) || 0 })}
                    />
                  </div>
                  <div>
                    <Label>Target Port</Label>
                    <Input
                      type="number"
                      placeholder="8080"
                      value={port.targetPort}
                      onChange={(e) => updatePort(port.id, { targetPort: parseInt(e.target.value) || 0 })}
                    />
                  </div>
                  <div>
                    <Label>Protocolo</Label>
                    <Select
                      value={port.protocol}
                      onValueChange={(value) => updatePort(port.id, { protocol: value as 'TCP' | 'UDP' })}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="TCP">TCP</SelectItem>
                        <SelectItem value="UDP">UDP</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <div className="text-xs text-muted-foreground">
                  DNS direto aos pods: Service Port {port.port} → Target Port {port.targetPort} ({port.protocol})
                </div>
              </CardContent>
            </Card>
          ))}
        </CardContent>
      </Card>

      {/* Actions */}
      <div className="flex items-center justify-between pt-6">
        <Button variant="outline" onClick={() => navigate(-1)}>
          <ArrowLeft className="h-4 w-4 mr-2" />
          Voltar
        </Button>
        <Button
          onClick={handleCreateService}
          disabled={creating || !serviceName.trim() || !selectorValue.trim()}
        >
          {creating ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Criando...
            </>
          ) : (
            <>
              <CheckCircle className="h-4 w-4 mr-2" />
              Criar Service Headless
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default ServiceCreateHeadlessPage;