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 { Textarea } from '@/components/ui/textarea';
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,
  Database,
  CheckCircle,
  Loader2,
  Settings,
  Image,
  HardDrive,
  Key,
} from 'lucide-react';

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

  const [deploymentName, setDeploymentName] = useState('');
  const [selectedNamespace, setSelectedNamespace] = useState(() => {
    return globalNamespace === 'all' ? 'default' : globalNamespace;
  });
  const [containerImage, setContainerImage] = useState('');
  const [containerPort, setContainerPort] = useState(5432);
  const [storageSize, setStorageSize] = useState('1Gi');
  const [databaseName, setDatabaseName] = useState('');
  const [databaseUser, setDatabaseUser] = useState('');
  const [databasePassword, setDatabasePassword] = useState('');
  const [creating, setCreating] = useState(false);

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

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

    if (!containerImage.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Imagem do container é obrigatória',
        variant: 'destructive',
      });
      return false;
    }

    if (!databaseName.trim() || !databaseUser.trim() || !databasePassword.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Configurações do banco de dados são obrigatórias',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

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

    setCreating(true);
    try {
      const deploymentYaml = `apiVersion: v1
kind: Secret
metadata:
  name: ${deploymentName}-secret
  namespace: ${selectedNamespace}
type: Opaque
data:
  POSTGRES_DB: ${btoa(databaseName)}
  POSTGRES_USER: ${btoa(databaseUser)}
  POSTGRES_PASSWORD: ${btoa(databasePassword)}
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: ${deploymentName}-pvc
  namespace: ${selectedNamespace}
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: ${storageSize}
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ${deploymentName}
  namespace: ${selectedNamespace}
  labels:
    app: ${deploymentName}
    tier: database
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: ${deploymentName}
  template:
    metadata:
      labels:
        app: ${deploymentName}
        tier: database
    spec:
      containers:
      - name: ${deploymentName}
        image: ${containerImage}
        ports:
        - containerPort: ${containerPort}
          name: db
        env:
        - name: POSTGRES_DB
          valueFrom:
            secretKeyRef:
              name: ${deploymentName}-secret
              key: POSTGRES_DB
        - name: POSTGRES_USER
          valueFrom:
            secretKeyRef:
              name: ${deploymentName}-secret
              key: POSTGRES_USER
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: ${deploymentName}-secret
              key: POSTGRES_PASSWORD
        - name: PGDATA
          value: /var/lib/postgresql/data/pgdata
        volumeMounts:
        - name: postgres-storage
          mountPath: /var/lib/postgresql/data
        livenessProbe:
          exec:
            command:
            - pg_isready
            - -U
            - \${POSTGRES_USER}
            - -d
            - \${POSTGRES_DB}
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          exec:
            command:
            - pg_isready
            - -U
            - \${POSTGRES_USER}
            - -d
            - \${POSTGRES_DB}
          initialDelaySeconds: 5
          periodSeconds: 5
        resources:
          requests:
            memory: "512Mi"
            cpu: "250m"
          limits:
            memory: "1Gi"
            cpu: "500m"
      volumes:
      - name: postgres-storage
        persistentVolumeClaim:
          claimName: ${deploymentName}-pvc
---
apiVersion: v1
kind: Service
metadata:
  name: ${deploymentName}-service
  namespace: ${selectedNamespace}
  labels:
    app: ${deploymentName}
    tier: database
spec:
  type: ClusterIP
  ports:
  - port: ${containerPort}
    targetPort: ${containerPort}
    protocol: TCP
    name: db
  selector:
    app: ${deploymentName}`;

      // Create temporary file with the deployment spec
      const tempFileName = `/tmp/deployment-database-${deploymentName}-${Date.now()}.yaml`;
      const writeCommand = `cat > "${tempFileName}" << 'EOF'
${deploymentYaml}
EOF`;

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

      // Apply the deployment
      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: 'Aplicação com Banco Criada com Sucesso',
          description: `Deployment, PVC, Secret e Service "${deploymentName}" foram criados no namespace "${selectedNamespace}"`,
          variant: 'success',
        });
        navigate('/workloads/deployments');
      } else {
        showToast({
          title: 'Erro ao Criar Aplicação com Banco',
          description: result.error || 'Falha ao criar o Deployment',
          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">
              <Database className="h-8 w-8 mr-3 text-orange-600" />
              Criar Aplicação com Banco
            </h1>
            <p className="text-muted-foreground">
              Configure uma aplicação com banco de dados e volumes persistentes
            </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="deploymentName">Nome da Aplicação</Label>
              <Input
                id="deploymentName"
                placeholder="ex: my-postgres, redis-cache"
                value={deploymentName}
                onChange={(e) => setDeploymentName(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>

      {/* Container Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Image className="h-5 w-5 mr-2" />
            Configuração do Container
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label htmlFor="containerImage">Imagem do Container</Label>
            <Input
              id="containerImage"
              placeholder="ex: postgres:15, mysql:8.0, redis:7-alpine"
              value={containerImage}
              onChange={(e) => setContainerImage(e.target.value)}
            />
            <p className="text-xs text-muted-foreground mt-1">
              Recomendado: postgres, mysql, redis, mongodb
            </p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="containerPort">Porta do Container</Label>
              <Select
                value={containerPort.toString()}
                onValueChange={(value) => setContainerPort(parseInt(value))}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="5432">5432 (PostgreSQL)</SelectItem>
                  <SelectItem value="3306">3306 (MySQL)</SelectItem>
                  <SelectItem value="6379">6379 (Redis)</SelectItem>
                  <SelectItem value="27017">27017 (MongoDB)</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="storageSize">Tamanho do Armazenamento</Label>
              <Select
                value={storageSize}
                onValueChange={setStorageSize}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1Gi">1Gi</SelectItem>
                  <SelectItem value="5Gi">5Gi</SelectItem>
                  <SelectItem value="10Gi">10Gi</SelectItem>
                  <SelectItem value="20Gi">20Gi</SelectItem>
                  <SelectItem value="50Gi">50Gi</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Database Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Key className="h-5 w-5 mr-2" />
            Configuração do Banco de Dados
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <Label htmlFor="databaseName">Nome do Banco</Label>
              <Input
                id="databaseName"
                placeholder="ex: myapp_db"
                value={databaseName}
                onChange={(e) => setDatabaseName(e.target.value)}
              />
            </div>
            <div>
              <Label htmlFor="databaseUser">Usuário</Label>
              <Input
                id="databaseUser"
                placeholder="ex: myapp_user"
                value={databaseUser}
                onChange={(e) => setDatabaseUser(e.target.value)}
              />
            </div>
            <div>
              <Label htmlFor="databasePassword">Senha</Label>
              <Input
                id="databasePassword"
                type="password"
                placeholder="Senha segura"
                value={databasePassword}
                onChange={(e) => setDatabasePassword(e.target.value)}
              />
            </div>
          </div>
          <div className="p-3 bg-orange-50 rounded-md border border-orange-200">
            <p className="text-sm text-orange-700">
              <strong>🔐 Segurança:</strong> As credenciais serão armazenadas em um Secret do Kubernetes
            </p>
          </div>
        </CardContent>
      </Card>

      {/* Storage Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <HardDrive className="h-5 w-5 mr-2" />
            Configuração de Armazenamento
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="p-3 bg-blue-50 rounded-md border border-blue-200">
            <p className="text-sm text-blue-700">
              <strong>📦 Volume Persistente:</strong> {storageSize} será criado automaticamente
            </p>
            <p className="text-xs text-blue-600 mt-1">
              Os dados do banco serão preservados mesmo se o pod for reiniciado
            </p>
          </div>
        </CardContent>
      </Card>

      {/* Features Summary */}
      <Card>
        <CardHeader>
          <CardTitle>Recursos Incluídos</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-2 text-sm">
            <p><strong>✓ Secret:</strong> Credenciais seguras do banco de dados</p>
            <p><strong>✓ PersistentVolumeClaim:</strong> Armazenamento persistente de {storageSize}</p>
            <p><strong>✓ Deployment:</strong> Uma réplica com estratégia Recreate</p>
            <p><strong>✓ Service:</strong> ClusterIP para comunicação interna</p>
            <p><strong>✓ Health Checks:</strong> Probes específicos para banco de dados</p>
            <p><strong>✓ Recursos:</strong> CPU 250m-500m, Memory 512Mi-1Gi</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={handleCreateDeployment}
          disabled={creating || !deploymentName.trim() || !containerImage.trim() || !databaseName.trim()}
        >
          {creating ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Criando...
            </>
          ) : (
            <>
              <CheckCircle className="h-4 w-4 mr-2" />
              Criar Aplicação com Banco
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default DeploymentCreateDatabasePage;