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';
import { Toaster } from "react-hot-toast";

export default function Banner(){
    const { data, setData, post, processing, errors, reset } = useForm({
        title: '',
        content: '',
        status: true,
        photo: '',
    });

    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_banner', {
            ...formResponse,
            preserveScroll: true,
        });
    }

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

            <div className="form-group">
                <label>Content</label>
                <textarea 
                    className="form-control"
                    rows="4"
                    value={data.content}
                    onChange={(e) => setData('content', e.target.value)}
                />
                {errors.content && <div className="invalid-feedback d-block">{errors.content}</div>}
            </div>

            <FileUploadInput label="Upload image (1900x1267)px" 
            buttonText={"Choose file (1900x1267)"}
            uploadUrl="/admin/api/banner/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>
        </>
    );
}