"use client";

import { useRef, useState } from "react";
import { Button } from "@/components/atoms/button";

interface ResidenceCardUploadInputProps {
  onSubmit: (file: File) => void;
  isPending: boolean;
  isError: boolean;
  error?: Error | null | undefined;
  submitLabel?: string | undefined;
  description?: string | undefined;
}

export function ResidenceCardUploadInput({
  onSubmit,
  isPending,
  isError,
  error,
  submitLabel = "Submit for review",
  description,
}: ResidenceCardUploadInputProps) {
  const [file, setFile] = useState<File | null>(null);
  const inputRef = useRef<HTMLInputElement | null>(null);

  const handleClear = () => {
    setFile(null);
    if (inputRef.current) {
      inputRef.current.value = "";
    }
  };

  const handleSubmit = () => {
    if (!file) return;
    onSubmit(file);
    handleClear();
  };

  return (
    <div className="space-y-3">
      {description && <p className="text-xs text-muted-foreground">{description}</p>}

      <input
        ref={inputRef}
        type="file"
        accept="image/*,application/pdf"
        onChange={e => setFile(e.target.files?.[0] ?? null)}
        className="block w-full text-sm text-foreground file:mr-4 file:py-2 file:px-3 file:rounded-md file:border-0 file:text-sm file:font-medium file:bg-muted file:text-foreground hover:file:bg-muted/80"
      />

      {file && (
        <div className="flex items-center justify-between gap-3 rounded-lg border border-border bg-muted/30 px-3 py-2">
          <div className="min-w-0">
            <div className="text-xs font-medium text-muted-foreground">Selected file</div>
            <div className="text-sm font-medium text-foreground truncate">{file.name}</div>
          </div>
          <Button type="button" variant="outline" size="sm" onClick={handleClear}>
            Change
          </Button>
        </div>
      )}

      <div className="flex items-center justify-end">
        <Button
          type="button"
          size="sm"
          disabled={!file || isPending}
          isLoading={isPending}
          loadingText="Uploading..."
          onClick={handleSubmit}
        >
          {submitLabel}
        </Button>
      </div>

      {isError && error && (
        <div className="text-sm text-destructive">
          {error instanceof Error ? error.message : "Failed to submit residence card."}
        </div>
      )}
    </div>
  );
}
