
import React from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { ExternalLink } from "lucide-react";

interface ProjectURLFieldProps {
  projectUrl: string;
  onProjectUrlChange: (value: string) => void;
}

const ProjectURLField = ({ projectUrl, onProjectUrlChange }: ProjectURLFieldProps) => {
  const handleUrlChange = (value: string) => {
    // If the user enters a URL without protocol, we'll store it as-is for display
    // but we'll add the protocol when saving
    onProjectUrlChange(value);
  };

  const normalizeUrl = (url: string): string => {
    if (!url) return url;
    
    // If URL already has a protocol, return as-is
    if (url.startsWith('http://') || url.startsWith('https://')) {
      return url;
    }
    
    // Add https:// prefix for URLs without protocol
    return `https://${url}`;
  };

  const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    const value = e.target.value.trim();
    if (value && !value.startsWith('http://') && !value.startsWith('https://')) {
      // Normalize the URL when the user leaves the field
      onProjectUrlChange(normalizeUrl(value));
    }
  };

  return (
    <div>
      <Label htmlFor="project_url" className="flex items-center gap-2">
        <ExternalLink className="h-4 w-4" />
        URL du projet (optionnel)
      </Label>
      <Input
        id="project_url"
        type="text"
        value={projectUrl}
        onChange={(e) => handleUrlChange(e.target.value)}
        onBlur={handleBlur}
        placeholder="www.exemple.com ou https://exemple.com"
      />
      <p className="text-sm text-gray-500 mt-1">
        Lien vers le site web, la démo ou le portfolio du projet. Le protocole https:// sera ajouté automatiquement si nécessaire.
      </p>
    </div>
  );
};

export default ProjectURLField;
