"use client";

import { useState } from "react";
import { Search } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";

export function CallsignSearch() {
  const [ident, setIdent] = useState("");
  const [result, setResult] = useState<{ ident: string; decode: string } | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSearch = async () => {
    if (!ident) return;

    setLoading(true);
    setError(null);
    setResult(null);

    try {
      const res = await fetch(`/api/callsign?callsign=${ident}`);
      if (!res.ok) {
        throw new Error("Failed to fetch data");
      }

      const data = await res.json();
      setResult({
        ident: data.ident,
        decode: data.decode
      });
    } catch (error) {
      setError("Error fetching callsign data. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex gap-2">
        <Input
          type="text"
          value={ident}
          onChange={(e) => setIdent(e.target.value)}
          placeholder="Enter IDENT"
          className="max-w-xs"
        />

        <Button onClick={handleSearch} className="gap-2" disabled={loading}>
          <Search className="h-4 w-4" />
          {loading ? "Searching..." : "Search"}
        </Button>
      </div>

      {loading && <p>Loading...</p>}

      {error && <p className="text-red-500">{error}</p>}

      {result && (
        <div className="space-y-2">
          <p>
            <span className="font-semibold">IDENT:</span> {result.ident}
          </p>
          <p>
            <span className="font-semibold">CALLSIGN:</span> {result.decode}
          </p>
        </div>
      )}
    </div>
  );
}
