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,
  Globe,
  CheckCircle,
  Loader2,
  Settings,
  ExternalLink,
} from 'lucide-react';

export function ServiceCreateExternalNamePage() {
  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 [externalName, setExternalName] = useState('');
  const [creating, setCreating] = useState(false);

  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 (!externalName.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Nome externo é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

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

    setCreating(true);
    try {
      const serviceYaml = `apiVersion: v1
kind: Service
metadata:
  name: ${serviceName}
  namespace: ${selectedNamespace}
spec:
  type: ExternalName
  externalName: ${externalName}`;

      // Create temporary file with the service spec
      const tempFileName = `/tmp/service-externalname-${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 ExternalName 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">
              <Globe className="h-8 w-8 mr-3 text-orange-600" />
              Criar Service ExternalName
            </h1>
            <p className="text-muted-foreground">
              Configure um alias DNS para um serviço externo
            </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: external-api"
                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>

      {/* External Service Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <ExternalLink className="h-5 w-5 mr-2" />
            Configuração do Serviço Externo
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label htmlFor="externalName">Nome Externo</Label>
            <Input
              id="externalName"
              placeholder="ex: api.example.com"
              value={externalName}
              onChange={(e) => setExternalName(e.target.value)}
            />
            <p className="text-xs text-muted-foreground mt-1">
              FQDN do serviço externo (exemplo.com, api.externa.com.br)
            </p>
          </div>
          
          {externalName && (
            <div className="p-3 bg-orange-50 rounded-md border border-orange-200">
              <p className="text-sm text-orange-700">
                <strong>Redirecionamento DNS:</strong>
              </p>
              <p className="text-xs text-orange-600 mt-1 font-mono">
                {serviceName || '<service-name>'}.{selectedNamespace}.svc.cluster.local → {externalName}
              </p>
            </div>
          )}
        </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() || !externalName.trim()}
        >
          {creating ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Criando...
            </>
          ) : (
            <>
              <CheckCircle className="h-4 w-4 mr-2" />
              Criar Service ExternalName
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default ServiceCreateExternalNamePage;