import { useFormik } from 'formik';
import * as Yup from 'yup';
import Modal from '../../components/Modals';
import { useState } from 'react';
import IconStar from '../../components/Icon/IconStar';
import Select from '../../components/Select';

interface Props {
    open: boolean;
    onClose: () => void;
    onSave: (data: any) => void;
    staffList?: any[];
    selectedMonth?: Date;
}

const AddReview = ({ open, onClose, onSave, staffList = [], selectedMonth }: Props) => {
    const [hoverRating, setHoverRating] = useState(0);

    const staffOptions = staffList.map(staff => ({
        value: staff.id,
        label: `${staff.name} (${staff.role})`
    }));

    const validationSchema = Yup.object({
        rating: Yup.number()
            .required('Rating is required')
            .min(1, 'Minimum 1 star')
            .max(5, 'Maximum 5 stars'),
        staff_id: Yup.number()
            .required('Staff Name is required'),
        comment: Yup.string()
            .required('Review is required')
            .min(5, 'Minimum 5 characters'),
        incentive: Yup.number()
            .min(0, 'Incentive cannot be negative')
    });

    const formik = useFormik({
        initialValues: {
            rating: 0,
            comment: '',
            staff_id: '',
            incentive: '',
        },
        validationSchema,
        onSubmit: (values) => {
            onSave({
                staff_id: values.staff_id,
                rating: values.rating,
                comment: values.comment,
                incentive: values.incentive || 0,
            });
            onClose();
        },
    });

    const renderStars = () => {
        return [...Array(5)].map((_, index) => {
            const starValue = index + 1;
            return (
                <span
                    key={index}
                    onClick={() => formik.setFieldValue('rating', starValue)}
                    onMouseEnter={() => setHoverRating(starValue)}
                    onMouseLeave={() => setHoverRating(0)}
                    className="cursor-pointer text-2xl"
                >
                    <IconStar
                        className={
                            starValue <= (hoverRating || formik.values.rating)
                                ? "text-yellow-400 fill-yellow-400"
                                : "text-gray-300"
                        }
                    />
                </span>
            );
        });
    };

    return (
        <Modal
            open={open}
            onClose={onClose}
            title={`Add Staff Review - ${selectedMonth?.toLocaleString('default', { month: 'long', year: 'numeric' })}`}
            footer={
                <>
                    <button onClick={onClose} className="btn btn-outline-danger" type="button">
                        Cancel
                    </button>
                    <button onClick={formik.handleSubmit as any} className="btn btn-primary" type="button">
                        Save Review
                    </button>
                </>
            }
        >
            <form className="space-y-4">
                <div>
                    <label className="text-xs text-gray-500">Staff <span className="text-red-500">*</span></label>
                    <Select
                        options={staffOptions}
                        value={staffOptions.find(o => o.value === formik.values.staff_id)}
                        onChange={(val: any) => {
                            formik.setFieldValue("staff_id", val.value);
                            formik.setFieldTouched("staff_id", true);
                        }}
                        placeholder="Select staff member"
                    />
                    {formik.touched.staff_id && formik.errors.staff_id && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.staff_id}</p>
                    )}
                </div>

                <div>
                    <label className="block mb-2 font-medium">Rating <span className="text-red-500">*</span></label>
                    <div className="flex gap-1">{renderStars()}</div>
                    {formik.touched.rating && formik.errors.rating && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.rating}</p>
                    )}
                </div>

                <div>
                    <label className="block mb-1 font-medium">Review <span className="text-red-500">*</span></label>
                    <textarea
                        name="comment"
                        className="form-textarea w-full"
                        rows={4}
                        placeholder="Write staff review..."
                        value={formik.values.comment}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                    />
                    {formik.touched.comment && formik.errors.comment && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.comment}</p>
                    )}
                </div>

                <div>
                    <label className="block mb-1 font-medium">Incentive Amount (₹)</label>
                    <input
                        type="number"
                        name="incentive"
                        className="form-input w-full"
                        placeholder="Enter incentive amount"
                        value={formik.values.incentive}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                        min="0"
                        step="1000"
                    />
                </div>
            </form>
        </Modal>
    );
};

export default AddReview;
