"use client";

import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { Credential } from "@/lib/api/credentials";

interface RotateCredentialDialogProps {
  credential: Credential | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSubmit: (id: string, newValue: string) => Promise<void>;
}

export function RotateCredentialDialog({
  credential,
  open,
  onOpenChange,
  onSubmit,
}: RotateCredentialDialogProps): React.ReactElement {
  const [newValue, setNewValue] = useState("");
  const [confirmValue, setConfirmValue] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.SyntheticEvent): Promise<void> => {
    e.preventDefault();
    if (!credential) return;

    setError(null);

    // Validation
    if (!newValue.trim()) {
      setError("New value is required");
      return;
    }
    if (newValue !== confirmValue) {
      setError("Values do not match");
      return;
    }

    setIsSubmitting(true);
    try {
      await onSubmit(credential.id, newValue);
      setNewValue("");
      setConfirmValue("");
      onOpenChange(false);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to rotate credential");
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!credential) return <></>;

  return (
    <Dialog
      open={open}
      onOpenChange={(open) => {
        onOpenChange(open);
        if (!open) {
          setNewValue("");
          setConfirmValue("");
          setError(null);
        }
      }}
    >
      <DialogContent className="sm:max-w-[525px]">
        <form onSubmit={handleSubmit}>
          <DialogHeader>
            <DialogTitle>Rotate Credential</DialogTitle>
            <DialogDescription>
              Replace the credential value with a new one. The old value will be permanently
              replaced.
            </DialogDescription>
          </DialogHeader>

          <div className="grid gap-4 py-4">
            {/* Credential Info */}
            <div className="rounded-lg bg-muted p-3">
              <p className="mb-1 font-medium">{credential.name}</p>
              <p className="text-sm text-muted-foreground">
                {credential.provider} • {credential.type.replace(/_/g, " ")}
              </p>
            </div>

            {/* New Value */}
            <div className="grid gap-2">
              <Label htmlFor="rotate-new-value">New Value *</Label>
              <Input
                id="rotate-new-value"
                type="password"
                value={newValue}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                  setNewValue(e.target.value);
                }}
                placeholder="Enter new credential value"
                disabled={isSubmitting}
              />
            </div>

            {/* Confirm Value */}
            <div className="grid gap-2">
              <Label htmlFor="rotate-confirm-value">Confirm New Value *</Label>
              <Input
                id="rotate-confirm-value"
                type="password"
                value={confirmValue}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                  setConfirmValue(e.target.value);
                }}
                placeholder="Re-enter new credential value"
                disabled={isSubmitting}
              />
            </div>

            {/* Warning */}
            <div className="rounded-lg border border-orange-200 bg-orange-50 p-3">
              <p className="text-sm text-orange-900">
                <strong>Note:</strong> This will permanently replace the existing credential value.
                The old value cannot be recovered after rotation.
              </p>
            </div>

            {/* Error Display */}
            {error && <div className="text-sm text-destructive">{error}</div>}
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                onOpenChange(false);
              }}
              disabled={isSubmitting}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting ? "Rotating..." : "Rotate Credential"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
