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 IconPhone from '../../components/Icon/IconPhone';
import IconUser from '../../components/Icon/IconUser';
import Avatar from '../../components/Avatar';
import userDefault from '../../assets/images/auth/user.png';

interface Props {
    open: boolean;
    onClose: () => void;
    onSave: (data: { rating: number; comment: string; incentive: number }) => void;
    data: any;
}

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

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

    // Formik
    const formik = useFormik({
        enableReinitialize: true,
        initialValues: {
            rating: data?.review?.rating || data?.rating || 0,
            comment: data?.review?.comment || data?.comment || '',
            incentive: data?.review?.incentive || data?.incentive || 0,
        },
        validationSchema,
        onSubmit: (values) => {
            onSave({
                rating: values.rating,
                comment: values.comment,
                incentive: values.incentive,
            });
            onClose();
        },
    });

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

    return (
        <Modal
            open={open}
            onClose={onClose}
            title={`Update Staff Review - ${data?.name || 'Staff'}`}
            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"
                    >
                        Update Review
                    </button>
                </>
            }
        >
            <form className="space-y-4">
                {/* Staff Information Display */}
                <div className="bg-gray-100 rounded-lg p-4">
                    <div className="flex justify-start items-center gap-3 mb-3">
                        <Avatar
                            src={data?.avatar}
                            size="md"
                            name={data?.name?.charAt(0)?.toUpperCase()}
                        />
                        <div>
                            <label className="text-black font-semibold text-base">
                                {data?.name || 'Staff Name'}
                            </label>
                            <div className="text-xs text-gray-500">
                                {data?.role || 'Role'}
                            </div>
                        </div>
                    </div>
                    <div className="grid grid-cols-2 gap-3 text-sm">
                        <div className="flex items-center gap-2">
                            <IconUser className="w-4 h-4 text-gray-500" />
                            <span className="text-gray-600">{data?.role || 'N/A'}</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <IconPhone className="w-4 h-4 text-gray-500" />
                            <span className="text-gray-600">{data?.phone || 'N/A'}</span>
                        </div>
                        <div className="flex items-center gap-2 col-span-2">
                            <span className="text-gray-500">Department:</span>
                            <span className="text-gray-700">{data?.department || 'N/A'}</span>
                        </div>
                    </div>
                </div>

                {/* Rating */}
                <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 as string}
                        </p>
                    )}
                </div>

                {/* Review Comment */}
                <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 as string}
                        </p>
                    )}
                </div>

                {/* Incentive */}
                <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"
                    />
                    {formik.touched.incentive && formik.errors.incentive && (
                        <p className="text-red-500 text-sm mt-1">
                            {formik.errors.incentive as string}
                        </p>
                    )}
                </div>

                {/* Performance Summary */}
                {data?.overall_score !== undefined && (
                    <div className="bg-blue-50 p-3 rounded-lg">
                        <div className="flex justify-between items-center mb-2">
                            <span className="text-sm font-medium text-blue-700">Current Performance Score</span>
                            <span className="text-sm font-bold text-blue-700">{data.overall_score}%</span>
                        </div>
                        <div className="w-full bg-blue-200 rounded-full h-1.5">
                            <div
                                className="bg-blue-600 h-1.5 rounded-full"
                                style={{ width: `${data.overall_score}%` }}
                            />
                        </div>
                        <p className="text-xs text-gray-500 mt-2">
                            Based on KRA/KPI achievements for the selected month
                        </p>
                    </div>
                )}
            </form>
        </Modal>
    );
};

export default EditReview;
