import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import ApiResponse from "@/components/ApiResponse";
import { krowSDK } from "@/api/krowSDK";
import { Card, CardHeader, CardTitle, CardContent, CardDescription } from "@/components/ui/card";

const UploadFile = () => {
  const [response, setResponse] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const [file, setFile] = useState(null);

  const handleFileChange = (e) => {
    setFile(e.target.files[0]);
  };

  const handleUpload = async (e) => {
    e.preventDefault();
    if (!file) {
      setError({ message: "Please select a file to upload." });
      return;
    }
    setLoading(true);
    setError(null);
    setResponse(null);

    try {
      const res = await krowSDK.integrations.Core.UploadFile({ file });
      setResponse(res);
    } catch (err) {
      setError(err.response?.data || err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <h1 className="text-3xl font-bold text-slate-900 mb-4">Upload Public File</h1>
      <p className="text-slate-600 mb-6">Tests the `integrations.Core.UploadFile` endpoint for public files.</p>
      
      <Card className="max-w-2xl">
        <CardHeader>
          <CardTitle>Test `/uploadFile`</CardTitle>
          <CardDescription>Handles multipart/form-data upload to GCS and returns a public URL.</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleUpload} className="space-y-4">
            <div>
              <Label htmlFor="file">File</Label>
              <Input id="file" type="file" onChange={handleFileChange} />
            </div>
            <Button type="submit" disabled={loading || !file}>
              {loading ? "Uploading..." : "Upload File"}
            </Button>
          </form>
        </CardContent>
      </Card>

      <ApiResponse response={response} error={error} loading={loading} />
    </div>
  );
};

export default UploadFile;
