"use client";

import { useState, useEffect } 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 { Textarea } from "@/components/ui/textarea";
import type { Credential } from "@/lib/api/credentials";

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

export interface EditCredentialFormData {
  name?: string;
  description?: string;
  expiresAt?: string;
}

export function EditCredentialDialog({
  credential,
  open,
  onOpenChange,
  onSubmit,
}: EditCredentialDialogProps): React.ReactElement {
  const [formData, setFormData] = useState<EditCredentialFormData>({
    name: "",
    description: "",
    expiresAt: "",
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Initialize form when credential changes
  useEffect(() => {
    if (credential) {
      const expiryDate = credential.expiresAt
        ? new Date(credential.expiresAt).toISOString().split("T")[0]
        : "";
      setFormData({
        name: credential.name,
        description: credential.description ?? "",
        ...(expiryDate && { expiresAt: expiryDate }),
      });
    }
  }, [credential]);

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

    setError(null);

    // Validation
    if (!formData.name?.trim()) {
      setError("Name is required");
      return;
    }

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

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

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[525px]">
        <form onSubmit={handleSubmit}>
          <DialogHeader>
            <DialogTitle>Edit Credential</DialogTitle>
            <DialogDescription>
              Update credential metadata. To change the value, use the Rotate option.
            </DialogDescription>
          </DialogHeader>

          <div className="grid gap-4 py-4">
            {/* Name */}
            <div className="grid gap-2">
              <Label htmlFor="edit-name">Name *</Label>
              <Input
                id="edit-name"
                value={formData.name}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                  setFormData({ ...formData, name: e.target.value });
                }}
                placeholder="e.g., GitHub Personal Token"
                disabled={isSubmitting}
              />
            </div>

            {/* Description */}
            <div className="grid gap-2">
              <Label htmlFor="edit-description">Description</Label>
              <Textarea
                id="edit-description"
                value={formData.description}
                onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => {
                  setFormData({ ...formData, description: e.target.value });
                }}
                placeholder="Optional description"
                disabled={isSubmitting}
                rows={3}
              />
            </div>

            {/* Expiry Date */}
            <div className="grid gap-2">
              <Label htmlFor="edit-expiresAt">Target Date</Label>
              <Input
                id="edit-expiresAt"
                type="date"
                value={formData.expiresAt}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                  setFormData({ ...formData, expiresAt: e.target.value });
                }}
                disabled={isSubmitting}
              />
              <p className="text-xs text-muted-foreground">
                Consider rotating the credential by this date
              </p>
            </div>

            {/* Provider & Type (read-only) */}
            <div className="rounded-lg bg-muted p-3">
              <p className="mb-2 text-sm font-medium">Read-Only Fields</p>
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="text-muted-foreground">Provider:</span>
                  <span className="ml-2">{credential.provider}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">Type:</span>
                  <span className="ml-2">{credential.type.replace(/_/g, " ")}</span>
                </div>
              </div>
            </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 ? "Saving..." : "Save Changes"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
