import { useState } from "react";
import apiClient from "../api/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Label } from "@/components/ui/label";

const ServiceTester = ({ serviceName, serviceDescription, endpoint, fields }) => {
  const [formData, setFormData] = useState({});
  const [response, setResponse] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  const handleChange = (e) => {
    const { name, value, files } = e.target;
    if (files) {
      setFormData({ ...formData, [name]: files[0] });
    } else {
      setFormData({ ...formData, [name]: value });
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setResponse(null);

    const data = new FormData();
    for (const key in formData) {
      data.append(key, formData[key]);
    }

    try {
      const res = await apiClient.post(endpoint, data);
      setResponse(res.data);
    } catch (err) {
      setError(err.response?.data || err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-4xl mx-auto">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-slate-900">{serviceName}</h1>
        <p className="text-slate-600 mt-1">{serviceDescription}</p>
      </div>

      <form onSubmit={handleSubmit}>
        <Card>
          <CardHeader>
            <CardTitle>Parameters</CardTitle>
            <CardDescription>
              Fill in the required parameters to execute the service.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {fields.map((field) => (
              <div key={field.name} className="grid w-full max-w-sm items-center gap-1.5">
                <Label htmlFor={field.name}>{field.label}</Label>
                {field.type === "textarea" ? (
                  <Textarea
                    id={field.name}
                    name={field.name}
                    onChange={handleChange}
                    placeholder={field.placeholder}
                  />
                ) : (
                  <Input
                    id={field.name}
                    name={field.name}
                    type={field.type}
                    onChange={handleChange}
                    placeholder={field.placeholder}
                  />
                )}
              </div>
            ))}
          </CardContent>
          <CardFooter>
            <Button type="submit" disabled={loading}>
              {loading ? "Executing..." : "Execute"}
            </Button>
          </CardFooter>
        </Card>
      </form>

      {response && (
        <div className="mt-8">
          <h2 className="text-xl font-bold text-slate-900 mb-2">Response</h2>
          <Card>
            <CardContent className="p-4">
              <pre className="text-sm overflow-x-auto bg-slate-900 text-white p-4 rounded-md">
                {JSON.stringify(response, null, 2)}
              </pre>
            </CardContent>
          </Card>
        </div>
      )}

      {error && (
        <div className="mt-8">
          <h2 className="text-xl font-bold text-red-600 mb-2">Error</h2>
          <Card className="border-red-500">
            <CardContent className="p-4">
              <pre className="text-sm overflow-x-auto bg-red-50 text-red-800 p-4 rounded-md">
                {JSON.stringify(error, null, 2)}
              </pre>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  );
};

export default ServiceTester;