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 CreateSignedUrl = () => {
  const [response, setResponse] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    file_uri: "gs://your-bucket/private-file.pdf",
    expires_in: 3600,
  });

  const handleChange = (e) => {
    const { id, value } = e.target;
    setFormData(prev => ({ ...prev, [id]: value }));
  };

  const handleCreateUrl = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setResponse(null);
    try {
      const params = {
        ...formData,
        expires_in: parseInt(formData.expires_in, 10),
      };
      const res = await krowSDK.integrations.Core.CreateFileSignedUrl(params);
      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">Create Signed URL</h1>
      <p className="text-slate-600 mb-6">Tests the `integrations.Core.CreateFileSignedUrl` endpoint.</p>
      
      <Card className="max-w-2xl">
        <CardHeader>
          <CardTitle>Test `/createSignedUrl`</CardTitle>
          <CardDescription>Creates a temporary access URL for a private file stored in GCS.</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleCreateUrl} className="space-y-4">
            <div>
              <Label htmlFor="file_uri">File URI</Label>
              <Input id="file_uri" value={formData.file_uri} onChange={handleChange} />
            </div>
            <div>
              <Label htmlFor="expires_in">Expires In (seconds)</Label>
              <Input id="expires_in" type="number" value={formData.expires_in} onChange={handleChange} />
            </div>
            <Button type="submit" disabled={loading}>
              {loading ? "Creating..." : "Create Signed URL"}
            </Button>
          </form>
        </CardContent>
      </Card>

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

export default CreateSignedUrl;
