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 Row from "@admin/ui/Row";
import { useForm } from "@inertiajs/react";
import { useEffect, useState } from 'react';
import FileUploadInput from "@admin/ui/forms/FileUploadInput";
import { useFormResponse } from '@/hooks/useFormResponse';
export default function Gallery(){
    const {data,setData,post,processing,errors,reset} = useForm({
        title: '',
        photo:'',
        caption: '',
        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);
        post('/admin/api/create_gallery',{
            ...formResponse,
            preserveScroll: true,
        });
    }

    return(
        <>
        <Row md="12" >
            <Col lg="12">
            <h2 className="page-title">Gallery</h2>
            <p className="text-muted">Manage gallery photos</p>
            <Row>
            <Col lg="12">
            <Card md="6" title="Add new image">
            <form onSubmit={handleSubmit}>
            <FormGroup label="Title" 
            value={data.title}
            onChange={(e) => setData('title', e.target.value)}
            invalidFeedback={errors.title}
            />

            <FileUploadInput label="Upload image (600x600)px" 
            buttonText={"Choose file (600x600)"}
            uploadUrl="/admin/api/gallery/upload_image"
            onSuccess={handleSuccess}
            onError={handleError}
            />

            <FormGroup
            id="caption"
            label="Caption"
            as="textarea"
            value={data.caption}
            helpText="Briefy describe what the image is about. Be precise not more than 255 characters"
            onChange={(e) => setData("caption", e.target.value)}
            rows="4"
            invalidFeedback={errors.caption}
            />
            
            <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>
        </>
    );
}