import { useState } from "react";
import { ChevronRight, Check, Plug } from "lucide-react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
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 { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";

const STEPS = ["Fournisseur", "Connexion", "Confirmation"];

const step1Schema = z.object({
  provider: z.enum(["openai", "anthropic", "azure", "mistral", "ollama"]),
});
const step2Schema = z.object({
  api_key: z.string().min(1, "La clé API est requise"),
  resource_name: z.string().optional(),
  deployment_id: z.string().optional(),
  base_url: z.string().optional(),
});

type Step1 = z.infer<typeof step1Schema>;
type Step2 = z.infer<typeof step2Schema>;

const PROVIDER_INFO: Record<
  string,
  { label: string; description: string; needsResource: boolean; needsBaseUrl: boolean }
> = {
  openai: {
    label: "OpenAI",
    description: "GPT-4o, GPT-4o-mini, GPT-3.5-turbo",
    needsResource: false,
    needsBaseUrl: false,
  },
  anthropic: {
    label: "Anthropic",
    description: "Claude 3.5 Sonnet, Claude 3 Opus, Claude 3 Haiku",
    needsResource: false,
    needsBaseUrl: false,
  },
  azure: {
    label: "Azure OpenAI",
    description: "Modèles OpenAI hébergés sur Azure",
    needsResource: true,
    needsBaseUrl: false,
  },
  mistral: {
    label: "Mistral AI",
    description: "Mistral Small, Mistral Large",
    needsResource: false,
    needsBaseUrl: false,
  },
  ollama: {
    label: "Ollama (local)",
    description: "Modèles locaux auto-hébergés",
    needsResource: false,
    needsBaseUrl: true,
  },
};

export function ProvidersPage() {
  const [step, setStep] = useState(0);
  const [step1Data, setStep1Data] = useState<Step1 | null>(null);
  const [step2Data, setStep2Data] = useState<Step2 | null>(null);
  const [completed, setCompleted] = useState(false);

  const form1 = useForm<Step1>({
    resolver: zodResolver(step1Schema),
    defaultValues: { provider: "openai" },
  });

  const form2 = useForm<Step2>({
    resolver: zodResolver(step2Schema),
    defaultValues: { api_key: "" },
  });

  const selectedProvider = form1.watch("provider");
  const info = PROVIDER_INFO[selectedProvider];

  const handleStep1 = form1.handleSubmit((data) => {
    setStep1Data(data);
    setStep(1);
  });

  const handleStep2 = form2.handleSubmit((data) => {
    setStep2Data(data);
    setStep(2);
  });

  const handleConfirm = () => {
    // Backend provider config API not yet implemented
    setCompleted(true);
  };

  if (completed) {
    return (
      <div className="flex flex-col items-center justify-center h-64 text-center space-y-4">
        <div className="h-12 w-12 rounded-full bg-green-100 flex items-center justify-center">
          <Check className="h-6 w-6 text-green-600" />
        </div>
        <div>
          <p className="font-semibold text-lg">Configuration sauvegardée</p>
          <p className="text-sm text-muted-foreground mt-1">
            Le fournisseur sera actif au prochain redémarrage du proxy.
          </p>
        </div>
        <Button onClick={() => { setStep(0); setCompleted(false); form1.reset(); form2.reset(); }}>
          Configurer un autre fournisseur
        </Button>
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-2xl">
      <div>
        <h2 className="text-xl font-bold">Fournisseurs IA</h2>
        <p className="text-sm text-muted-foreground">
          Configurez vos connexions aux fournisseurs LLM
        </p>
      </div>

      <Alert>
        <Plug className="h-4 w-4" />
        <AlertTitle>Configuration via variables d&apos;environnement</AlertTitle>
        <AlertDescription>
          Les clés API sont actuellement gérées via des variables d&apos;environnement dans
          docker-compose.yml. L&apos;interface de gestion dynamique sera disponible dans un prochain sprint.
        </AlertDescription>
      </Alert>

      {/* Step indicator */}
      <div className="flex items-center gap-2">
        {STEPS.map((label, idx) => (
          <div key={label} className="flex items-center gap-2">
            <div
              className={cn(
                "h-7 w-7 rounded-full flex items-center justify-center text-xs font-semibold",
                idx < step
                  ? "bg-green-100 text-green-700"
                  : idx === step
                  ? "bg-primary text-primary-foreground"
                  : "bg-muted text-muted-foreground"
              )}
            >
              {idx < step ? <Check className="h-3.5 w-3.5" /> : idx + 1}
            </div>
            <span className={cn("text-sm", idx === step ? "font-medium" : "text-muted-foreground")}>
              {label}
            </span>
            {idx < STEPS.length - 1 && <ChevronRight className="h-4 w-4 text-muted-foreground" />}
          </div>
        ))}
      </div>

      {/* Step 1: Choose provider */}
      {step === 0 && (
        <form onSubmit={handleStep1} className="space-y-4 rounded-lg border p-6">
          <h3 className="font-semibold">Choisir un fournisseur</h3>
          <div className="grid grid-cols-1 gap-3">
            {Object.entries(PROVIDER_INFO).map(([key, pinfo]) => (
              <label
                key={key}
                className={cn(
                  "flex items-center gap-4 p-4 rounded-lg border cursor-pointer transition-colors",
                  selectedProvider === key
                    ? "border-primary bg-primary/5"
                    : "hover:border-muted-foreground/40"
                )}
              >
                <input
                  type="radio"
                  value={key}
                  {...form1.register("provider")}
                  className="accent-primary"
                />
                <div>
                  <p className="font-medium text-sm">{pinfo.label}</p>
                  <p className="text-xs text-muted-foreground">{pinfo.description}</p>
                </div>
                {selectedProvider === key && (
                  <Badge variant="outline" className="ml-auto">Sélectionné</Badge>
                )}
              </label>
            ))}
          </div>
          <Button type="submit" className="w-full">
            Suivant <ChevronRight className="h-4 w-4 ml-1" />
          </Button>
        </form>
      )}

      {/* Step 2: Connection details */}
      {step === 1 && step1Data && (
        <form onSubmit={handleStep2} className="space-y-4 rounded-lg border p-6">
          <h3 className="font-semibold">Paramètres de connexion — {info.label}</h3>

          {info.needsBaseUrl ? (
            <div className="space-y-1">
              <Label htmlFor="base_url">URL de base</Label>
              <Input
                id="base_url"
                {...form2.register("base_url")}
                placeholder="http://localhost:11434/v1"
              />
            </div>
          ) : (
            <div className="space-y-1">
              <Label htmlFor="api_key">Clé API *</Label>
              <Input
                id="api_key"
                type="password"
                {...form2.register("api_key")}
                placeholder="sk-..."
              />
              {form2.formState.errors.api_key && (
                <p className="text-xs text-destructive">
                  {form2.formState.errors.api_key.message}
                </p>
              )}
            </div>
          )}

          {info.needsResource && (
            <>
              <div className="space-y-1">
                <Label htmlFor="resource_name">Resource Name (Azure)</Label>
                <Input
                  id="resource_name"
                  {...form2.register("resource_name")}
                  placeholder="my-azure-resource"
                />
              </div>
              <div className="space-y-1">
                <Label htmlFor="deployment_id">Deployment ID</Label>
                <Input
                  id="deployment_id"
                  {...form2.register("deployment_id")}
                  placeholder="gpt-4o"
                />
              </div>
            </>
          )}

          <div className="flex gap-2">
            <Button type="button" variant="outline" onClick={() => setStep(0)}>
              Retour
            </Button>
            <Button type="submit" className="flex-1">
              Suivant <ChevronRight className="h-4 w-4 ml-1" />
            </Button>
          </div>
        </form>
      )}

      {/* Step 3: Confirmation */}
      {step === 2 && step1Data && step2Data && (
        <div className="space-y-4 rounded-lg border p-6">
          <h3 className="font-semibold">Confirmation</h3>
          <div className="space-y-2 text-sm">
            <div className="flex justify-between py-2 border-b">
              <span className="text-muted-foreground">Fournisseur</span>
              <span className="font-medium">{PROVIDER_INFO[step1Data.provider].label}</span>
            </div>
            {step2Data.api_key && (
              <div className="flex justify-between py-2 border-b">
                <span className="text-muted-foreground">Clé API</span>
                <span className="font-mono">{step2Data.api_key.slice(0, 8)}••••••••</span>
              </div>
            )}
            {step2Data.base_url && (
              <div className="flex justify-between py-2 border-b">
                <span className="text-muted-foreground">URL</span>
                <span className="font-mono">{step2Data.base_url}</span>
              </div>
            )}
            {step2Data.resource_name && (
              <div className="flex justify-between py-2 border-b">
                <span className="text-muted-foreground">Resource</span>
                <span className="font-mono">{step2Data.resource_name}</span>
              </div>
            )}
          </div>
          <Alert variant="warning">
            <AlertDescription>
              La configuration sera appliquée via une variable d&apos;environnement. Vous devrez
              redémarrer le service proxy pour l&apos;activer.
            </AlertDescription>
          </Alert>
          <div className="flex gap-2">
            <Button type="button" variant="outline" onClick={() => setStep(1)}>
              Retour
            </Button>
            <Button onClick={handleConfirm} className="flex-1">
              <Check className="h-4 w-4 mr-2" /> Confirmer
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
