/* global wp */
import React, { useState, useEffect } from 'react';
import { Card, Button, Input, Select } from '../../../components/ui';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';

const FeedbackTab = ({ addNotice }) => {
  const supportForumUrl = 'https://wordpress.org/support/plugin/prorank-seo/';
  const [feedbackType, setFeedbackType] = useState('feature');
  const [subject, setSubject] = useState('');
  const [message, setMessage] = useState('');
  const [priority, setPriority] = useState('medium');
  const [email, setEmail] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [recentFeedback, setRecentFeedback] = useState([]);
  const [isLoadingFeedback, setIsLoadingFeedback] = useState(false);
  const [feedbackStats, setFeedbackStats] = useState([]);

  const feedbackTypes = [
    { label: __('Feature Request', 'prorank-seo'), value: 'feature' },
    { label: __('Bug Report', 'prorank-seo'), value: 'bug' },
    { label: __('General Feedback', 'prorank-seo'), value: 'general' },
  ];

  const priorities = [
    { label: __('Low', 'prorank-seo'), value: 'low' },
    { label: __('Medium', 'prorank-seo'), value: 'medium' },
    { label: __('High', 'prorank-seo'), value: 'high' },
  ];

  const formatFeedbackDate = (dateString) => {
    if (!dateString) {
      return '';
    }

    try {
      const date = new Date(dateString);
      if (Number.isNaN(date.getTime())) {
        return dateString;
      }

      return date.toLocaleDateString(undefined, {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
      });
    } catch (error) {
      return dateString;
    }
  };

  const getStatusLabel = (status) => {
    switch (status) {
      case 'resolved':
        return __('Resolved', 'prorank-seo');
      case 'in_progress':
        return __('In Progress', 'prorank-seo');
      case 'reviewed':
        return __('Reviewed', 'prorank-seo');
      default:
        return __('Pending', 'prorank-seo');
    }
  };

  const handleSubmit = async () => {
    if (!subject.trim() || !message.trim()) {
      addNotice('error', __('Please fill in all required fields', 'prorank-seo'));
      return;
    }

    setIsSubmitting(true);

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/feedback/submit',
        method: 'POST',
        data: {
          type: feedbackType,
          subject,
          message,
          priority,
          email,
        },
      });

      if (response.success) {
        addNotice(
          'success',
          response.message || __("Thank you for your feedback! We'll review it soon.", 'prorank-seo')
        );
        // Reset form
        setSubject('');
        setMessage('');
        setPriority('medium');
        setEmail('');
        // Refresh feedback list
        fetchRecentFeedback();
      } else {
        addNotice('error', response.message || __('Failed to submit feedback', 'prorank-seo'));
      }
    } catch (error) {
      addNotice('error', error.message || __('Failed to submit feedback', 'prorank-seo'));
    } finally {
      setIsSubmitting(false);
    }
  };

  const getTemplateMessage = (type) => {
    switch (type) {
      case 'bug':
        return __(
          'Steps to reproduce:\n1. \n2. \n3. \n\nExpected behavior:\n\nActual behavior:\n\nBrowser/Device:',
          'prorank-seo'
        );
      case 'feature':
        return __('Feature description:\n\nUse case:\n\nExpected benefit:', 'prorank-seo');
      default:
        return '';
    }
  };

  React.useEffect(() => {
    const template = getTemplateMessage(feedbackType);
    if (template && !message) {
      setMessage(template);
    }
  }, [feedbackType]);

  // Fetch recent feedback on component mount
  useEffect(() => {
    fetchRecentFeedback();
  }, []);

  const fetchRecentFeedback = async () => {
    setIsLoadingFeedback(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/feedback/list?limit=5',
        method: 'GET',
      });

      if (response.data) {
        setRecentFeedback(response.data.feedback || []);
        setFeedbackStats(response.data.stats || []);
      }
    } catch (error) {
      // Silently handle error - feedback list is optional
    } finally {
      setIsLoadingFeedback(false);
    }
  };

  return (
    <div className="prorank-feedback-tab">
      <div className="prorank-section-header">
        <h2 className="prorank-section-title">
          {__('Feedback & Feature Requests', 'prorank-seo')}
        </h2>
        <p className="prorank-section-description">
          {__(
            'Share feature ideas, bug reports, and product feedback. For setup help, use the WordPress.org support forum.',
            'prorank-seo'
          )}
        </p>
      </div>

      <div className="prorank-support-grid">
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">
              {__('Submit Feedback', 'prorank-seo')}
            </h3>
          </div>
          <div className="prorank-card-body">
            <p className="prorank-card-description">
              {__(
                'Use this form for product feedback, feature requests, and bug reports. Free-plugin support questions should go to the WordPress.org support forum.',
                'prorank-seo'
              )}
            </p>

            <div className="prorank-settings-actions" style={{ marginBottom: '16px' }}>
              <Button
                variant="secondary"
                onClick={() => window.open(supportForumUrl, '_blank')}
              >
                {__('Open Support Forum', 'prorank-seo')}
              </Button>
            </div>

            <Select
              label={__('Feedback Type', 'prorank-seo')}
              value={feedbackType}
              options={feedbackTypes}
              onChange={(value) => setFeedbackType(value)}
            />

            <Input
              label={__('Subject *', 'prorank-seo')}
              value={subject}
              onChange={setSubject}
              placeholder={__('Brief description of your feedback', 'prorank-seo')}
            />

            <div className="form-group">
              <label>{__('Message *', 'prorank-seo')}</label>
              <textarea
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                rows={8}
                className="prorank-textarea"
              />
              <p className="help-text">{__('Please be as detailed as possible', 'prorank-seo')}</p>
            </div>

            {feedbackType === 'bug' && (
              <Select
                label={__('Priority', 'prorank-seo')}
                value={priority}
                options={priorities}
                onChange={(value) => setPriority(value)}
              />
            )}

            <Input
              label={__('Email (optional)', 'prorank-seo')}
              value={email}
              onChange={setEmail}
              type="email"
              helperText={__("If you'd like us to follow up with you", 'prorank-seo')}
            />

            <div className="prorank-settings-actions">
              <Button
                variant="primary"
                onClick={handleSubmit}
                disabled={isSubmitting || !subject.trim() || !message.trim()}
              >
                {isSubmitting ? __('Submitting…', 'prorank-seo') : __('Submit Feedback', 'prorank-seo')}
              </Button>
            </div>
          </div>
        </Card>

        {isLoadingFeedback && (
          <Card className="prorank-card--modern">
            <div className="prorank-card-header">
              <h3 className="prorank-card-title">
                {__('Your Recent Feedback', 'prorank-seo')}
              </h3>
            </div>
            <div className="prorank-card-body">
              <p className="prorank-card-description">
                {__('Loading recent feedback…', 'prorank-seo')}
              </p>
            </div>
          </Card>
        )}

        {!isLoadingFeedback && recentFeedback.length > 0 && (
          <Card className="prorank-card--modern">
            <div className="prorank-card-header">
              <h3 className="prorank-card-title">
                {__('Your Recent Feedback', 'prorank-seo')}
              </h3>
            </div>
            <div className="prorank-card-body">
              <p className="prorank-card-description">
                {__('Track the latest feedback items received for this site.', 'prorank-seo')}
              </p>

              <div className="prorank-feedback-list">
                {recentFeedback.map((item) => (
                  <div key={item.id} className="prorank-feedback-item" style={{
                    padding: '16px',
                    marginTop: '12px',
                    border: '1px solid #e5e7eb',
                    borderRadius: '8px',
                    background: '#f9fafb',
                  }}>
                    <div style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      gap: '12px',
                      marginBottom: '8px',
                      flexWrap: 'wrap',
                    }}>
                      <strong>{item.subject}</strong>
                      <span style={{ color: '#6b7280', fontSize: '12px' }}>
                        {formatFeedbackDate(item.createdAt)}
                      </span>
                    </div>

                    <div style={{
                      display: 'flex',
                      gap: '8px',
                      flexWrap: 'wrap',
                      marginBottom: '8px',
                      fontSize: '12px',
                      color: '#4b5563',
                    }}>
                      <span>{item.type}</span>
                      {item.priority && <span>• {item.priority}</span>}
                      <span>• {getStatusLabel(item.status)}</span>
                    </div>

                    {item.message && (
                      <p style={{ margin: 0, color: '#6b7280' }}>
                        {item.message}
                      </p>
                    )}
                  </div>
                ))}
              </div>
            </div>
          </Card>
        )}

      </div>

    </div>
  );
};

export default FeedbackTab;
