import React, { useState, useEffect } from 'react';
import Card from '../components/Card';
import Button from '../components/Button';
import { api } from '../utils/api';
import type { HistoryItem } from '../types';

const History: React.FC = () => {
  const [history, setHistory] = useState<HistoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  useEffect(() => {
    loadHistory();
  }, [page]);

  const loadHistory = async () => {
    setLoading(true);
    try {
      const data = await api.getHistory(page);
      setHistory(data.items);
      setTotalPages(data.total_pages);
    } catch (error) {
      console.error('Failed to load history:', error);
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString();
  };

  const getStatusBadge = (status: string) => {
    const badges = {
      success: { label: 'Success', className: 'pstb-badge-success' },
      failed: { label: 'Failed', className: 'pstb-badge-error' },
      pending: { label: 'Pending', className: 'pstb-badge-pending' },
    };
    const badge = badges[status as keyof typeof badges] || badges.pending;
    return <span className={`pstb-badge ${badge.className}`}>{badge.label}</span>;
  };

  if (loading && page === 1) {
    return <div className="pstb-loading">Loading history...</div>;
  }

  return (
    <div className="pstb-history">
      <Card title="Generation History">
        {history.length === 0 ? (
          <div className="pstb-empty-state">
            <p>No generation history yet. Start by generating some content!</p>
          </div>
        ) : (
          <>
            <div className="pstb-history-list">
              {history.map((item) => (
                <div key={item.id} className="pstb-history-item">
                  <div className="pstb-history-header">
                    <div className="pstb-history-title">
                      <strong>{item.parameters.topic || 'Untitled'}</strong>
                      {getStatusBadge(item.status)}
                    </div>
                    <div className="pstb-history-date">{formatDate(item.created_at)}</div>
                  </div>

                  <div className="pstb-history-details">
                    <div className="pstb-history-meta">
                      <span className="pstb-meta-item">
                        <strong>Provider:</strong> {item.ai_provider}
                      </span>
                      <span className="pstb-meta-item">
                        <strong>Post Type:</strong> {item.parameters.post_type || 'post'}
                      </span>
                      <span className="pstb-meta-item">
                        <strong>Tone:</strong> {item.parameters.tone || 'N/A'}
                      </span>
                      <span className="pstb-meta-item">
                        <strong>Length:</strong> {item.parameters.length || 'N/A'}
                      </span>
                    </div>

                    {item.parameters.target_audience && (
                      <div className="pstb-meta-item">
                        <strong>Target Audience:</strong> {item.parameters.target_audience}
                      </div>
                    )}

                    {item.parameters.seo_keywords && (
                      <div className="pstb-meta-item">
                        <strong>SEO Keywords:</strong> {item.parameters.seo_keywords}
                      </div>
                    )}

                    {item.error_message && (
                      <div className="pstb-error-message">
                        <strong>Error:</strong> {item.error_message}
                      </div>
                    )}

                    {item.post_id && (
                      <div className="pstb-history-actions">
                        <a
                          href={`/wp-admin/post.php?post=${item.post_id}&action=edit`}
                          className="pstb-link"
                          target="_blank"
                          rel="noopener noreferrer"
                        >
                          Edit Post
                        </a>
                        <a
                          href={`/?p=${item.post_id}`}
                          className="pstb-link"
                          target="_blank"
                          rel="noopener noreferrer"
                        >
                          View Post
                        </a>
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>

            {totalPages > 1 && (
              <div className="pstb-pagination">
                <Button
                  variant="secondary"
                  disabled={page === 1}
                  onClick={() => setPage((p) => p - 1)}
                >
                  Previous
                </Button>
                <span className="pstb-page-info">
                  Page {page} of {totalPages}
                </span>
                <Button
                  variant="secondary"
                  disabled={page === totalPages}
                  onClick={() => setPage((p) => p + 1)}
                >
                  Next
                </Button>
              </div>
            )}
          </>
        )}
      </Card>
    </div>
  );
};

export default History;
