import Card from "@admin/ui/Card";
import Col from "@admin/ui/Col";
import FormGroup from "@admin/ui/forms/FormGroup";
import Switch from "@admin/ui/forms/Switch";
import FileUploadInput from "@admin/ui/forms/FileUploadInput";
import Row from "@admin/ui/Row";
import { useForm } from "@inertiajs/react";
import { useFormResponse } from '@/hooks/useFormResponse';

export default  function Testimonial(){
    const {data, setData,post, processing, errors,reset} = useForm({
        name: '',
        message: '',
        photo: '',
        status: true,
    });

    const handleSuccess = (filename) => {
        setData('photo',filename);
    };

    const handleError = (error) => {
        console.error("Upload error:", error);
    };

    const handleSubmit = (event) => {
        event.preventDefault();
        const formResponse = useFormResponse(reset);
        // api request
        post('/admin/api/create_testimonial', {
            ...formResponse,
            preserveScroll: true, 
        });
    };

    return(
        <>
        <Row md="12" >
            <Col lg="12">
            <h2 className="page-title">Create New Testimonial</h2>
            <p className="text-muted">Add  testimonials to be featured on the website</p>
            <Row>
            <Col lg="12">
            <Card md="6" title="New Testimonial">
            <form  onSubmit={handleSubmit}>
            <FormGroup label="Name" 
            value={data.name}
            onChange={(e) => setData('name', e.target.value)}
            invalidFeedback={errors.name}
            />
            
            <FormGroup
            id="message"
            label="Message"
            as="textarea"
            value={data.message}
            onChange={(e) => setData('message', e.target.value)}
            rows="4"
            invalidFeedback={errors.message}
            />

            <br />
            <FileUploadInput label="Upload Photo (400x400)px"
            buttonText={"Choose file (400x400)"}
            inputId="customFileUpload"
            uploadUrl="/admin/api/testimonial/upload_image"
            onSuccess={handleSuccess}
            onError={handleError} />

            <Switch
            id="customSwitch"
            label="Active"
            checked={data.status}
            onChange={({ target: { checked } }) =>
                setData(prevData => ({ ...prevData, status: checked }))
                }                  
                />
                <br/>
            <button type="submit" className="btn btn-primary " disabled={processing}>Save</button>
            </form>
            </Card>
            </Col>
            </Row>
            </Col>
        </Row>
        </>
    );
}