import { useSelect, useDispatch } from '@wordpress/data';
import { useState, useMemo, useCallback } from '@wordpress/element';
import {
  PanelRow,
  ComboboxControl,
  Button,
  Spinner,
  __experimentalHStack as HStack,
  __experimentalText as Text,
} from '@wordpress/components';
import { store as noticesStore } from '@wordpress/notices';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { STORE_NAME } from '../store';

const { flowEW } = window;
const { restUrl, postId, currentUserCan, i18n } = flowEW;

export default function ReviewerField() {
  const review = useSelect((sel) => sel(STORE_NAME).getReview(), []);
  const reviewers = useSelect((sel) => sel(STORE_NAME).getReviewers(), []);
  const { setReview } = useDispatch(STORE_NAME);
  const { createSuccessNotice, createErrorNotice } = useDispatch(noticesStore);

  const [isEditing, setIsEditing] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [filterValue, setFilterValue] = useState('');

  const reviewerId = review ? Number(review.reviewer?.id || review.reviewer_id) : 0;
  const reviewerData = reviewerId
    ? (review.reviewer || reviewers.find((u) => u.id === reviewerId) || null)
    : null;
  const hasReviewer = !!reviewerData;
  const canAssign = currentUserCan.assignReviewer;
  const showCombobox = canAssign && (!hasReviewer || isEditing);

  const reviewerOptions = useMemo(
    () => reviewers.map((u) => ({ value: String(u.id), label: u.name })),
    [reviewers]
  );

  const filteredOptions = useMemo(() => {
    if (!filterValue) return reviewerOptions;
    const lower = filterValue.toLowerCase();
    return reviewerOptions.filter((o) => o.label.toLowerCase().includes(lower));
  }, [reviewerOptions, filterValue]);

  const handleSelect = useCallback(async (val) => {
    if (!val) return;
    const newId = Number(val);
    if (newId === reviewerId) {
      setIsEditing(false);
      return;
    }
    setIsSaving(true);
    try {
      const data = await apiFetch({
        url: `${restUrl}/reviews`,
        method: 'POST',
        data: { post_id: postId, reviewer_id: newId },
      });
      setReview(data);
      setIsEditing(false);
      setFilterValue('');
      createSuccessNotice(__('\u2714 Reviewer assigned.', 'jumplinks-editorial-workflow'), { type: 'snackbar', isDismissible: true });
    } catch (err) {
      createErrorNotice(err?.message || __('Failed to assign reviewer.', 'jumplinks-editorial-workflow'), { isDismissible: true });
    } finally {
      setIsSaving(false);
    }
  }, [reviewerId]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleRemove = useCallback(async () => {
    if (!review) return;
    setIsSaving(true);
    try {
      const data = await apiFetch({ url: `${restUrl}/reviews/${review.id}/cancel`, method: 'POST' });
      setReview(data || null);
      setIsEditing(false);
      setFilterValue('');
      createSuccessNotice(__('\u2714 Reviewer removed.', 'jumplinks-editorial-workflow'), { type: 'snackbar', isDismissible: true });
    } catch (err) {
      createErrorNotice(err?.message || __('Failed to remove reviewer.', 'jumplinks-editorial-workflow'), { isDismissible: true });
    } finally {
      setIsSaving(false);
    }
  }, [review]); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <PanelRow>
      <div style={{ width: '100%' }}>
        <HStack justify="space-between" className="flow-ew-label-row">
          <span className="flow-ew-field-label">{i18n.reviewer}</span>
          {canAssign && hasReviewer && (
            <Button
              variant="link"
              onClick={() => {
                setIsEditing((v) => !v);
                setFilterValue('');
              }}
              className="flow-ew-link-btn"
            >
              {isEditing ? i18n.cancelEdit : i18n.editReviewer}
            </Button>
          )}
        </HStack>

        {hasReviewer && !isEditing && (
          <div className="flow-ew-reviewer-card">
            <div className="flow-ew-reviewer-card__main">
              {reviewerData.avatar_url && (
                <img
                  src={reviewerData.avatar_url}
                  alt=""
                  width={24}
                  height={24}
                  className="flow-ew-avatar"
                />
              )}
              <Text size="13" className="flow-ew-truncate">
                {reviewerData.name || reviewerData.email}
              </Text>
            </div>
            {canAssign && (
              <Button
                icon="no-alt"
                label={i18n.removeReviewer}
                isSmall
                onClick={handleRemove}
                disabled={isSaving}
                className="flow-ew-reviewer-card__remove"
              />
            )}
          </div>
        )}

        {showCombobox && (
          <div className="flow-ew-reviewer-combobox">
            <ComboboxControl
              className="flow-ew-reviewer-combobox__control"
              hideLabelFromVision
              label={i18n.selectReviewer}
              placeholder={
                i18n.reviewerPlaceholder ||
                __(
                  'assign a dedicated reviewer',
                  'jumplinks-editorial-workflow'
                )
              }
              value={null}
              onChange={handleSelect}
              options={reviewerOptions}
              filteredOptions={filteredOptions}
              onFilterValueChange={setFilterValue}
              disabled={isSaving}
              __next40pxDefaultSize
              __nextHasNoMarginBottom
            />
            {isSaving && (
              <div className="flow-ew-spinner-overlay">
                <Spinner />
              </div>
            )}
          </div>
        )}
      </div>
    </PanelRow>
  );
}
