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

const SendEmail = () => {
  const [response, setResponse] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    to: "test@example.com",
    subject: "Test Email from Harness",
    body: "This is a test email.",
  });

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

  const handleSendEmail = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setResponse(null);
    try {
      const res = await krowSDK.integrations.Core.SendEmail(formData);
      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">Send Email</h1>
      <p className="text-slate-600 mb-6">Tests the `integrations.Core.SendEmail` endpoint.</p>
      
      <Card className="max-w-2xl">
        <CardHeader>
          <CardTitle>Test `/sendEmail`</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSendEmail} className="space-y-4">
            <div>
              <Label htmlFor="to">To</Label>
              <Input id="to" type="email" value={formData.to} onChange={handleChange} />
            </div>
            <div>
              <Label htmlFor="subject">Subject</Label>
              <Input id="subject" value={formData.subject} onChange={handleChange} />
            </div>
            <div>
              <Label htmlFor="body">Body</Label>
              <Textarea id="body" value={formData.body} onChange={handleChange} rows={5} />
            </div>
            <Button type="submit" disabled={loading}>
              {loading ? "Sending..." : "Send Email"}
            </Button>
          </form>
        </CardContent>
      </Card>

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

export default SendEmail;
