import React, { useState, useEffect } from 'react';

interface Deal {
  id: number;
  title: string;
  value: number;
  currency: string;
  status: string;
  stage_id: number;
  stage_name?: string;
  person_name?: string;
  org_name?: string;
  owner_name?: string;
  add_time: string;
  expected_close_date?: string;
}

type SortField = 'title' | 'value' | 'add_time' | 'expected_close_date';
type SortDirection = 'asc' | 'desc';

function App() {
  const [deals, setDeals] = useState<Deal[]>([]);
  const [filteredDeals, setFilteredDeals] = useState<Deal[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all_not_deleted');
  const [sortField, setSortField] = useState<SortField>('add_time');
  const [sortDirection, setSortDirection] = useState<SortDirection>('desc');

  useEffect(() => {
    loadDeals();
  }, [statusFilter]);

  useEffect(() => {
    filterAndSortDeals();
  }, [deals, searchTerm, sortField, sortDirection]);

  const loadDeals = async () => {
    setLoading(true);
    try {
      const response = await fetch('/mcp/pipedrive_deals_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: statusFilter, limit: 500 })
      });
      const data = await response.json();
      setDeals(data.data || []);
    } catch (error) {
      console.error('Failed to load deals:', error);
    } finally {
      setLoading(false);
    }
  };

  const filterAndSortDeals = () => {
    let filtered = [...deals];

    // Apply search filter
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      filtered = filtered.filter(deal =>
        deal.title.toLowerCase().includes(term) ||
        deal.person_name?.toLowerCase().includes(term) ||
        deal.org_name?.toLowerCase().includes(term)
      );
    }

    // Apply sorting
    filtered.sort((a, b) => {
      let aVal: any = a[sortField];
      let bVal: any = b[sortField];

      if (sortField === 'add_time' || sortField === 'expected_close_date') {
        aVal = new Date(aVal || 0).getTime();
        bVal = new Date(bVal || 0).getTime();
      }

      if (aVal < bVal) return sortDirection === 'asc' ? -1 : 1;
      if (aVal > bVal) return sortDirection === 'asc' ? 1 : -1;
      return 0;
    });

    setFilteredDeals(filtered);
  };

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortDirection('asc');
    }
  };

  const formatCurrency = (amount: number, currency = 'USD') => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency,
      minimumFractionDigits: 0
    }).format(amount);
  };

  const formatDate = (dateStr: string) => {
    if (!dateStr) return 'N/A';
    return new Date(dateStr).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  };

  const SortIcon: React.FC<{ field: SortField }> = ({ field }) => {
    if (sortField !== field) return <span className="sort-icon">⇅</span>;
    return <span className="sort-icon active">{sortDirection === 'asc' ? '↑' : '↓'}</span>;
  };

  if (loading) {
    return <div className="loading">Loading deals...</div>;
  }

  return (
    <div className="app">
      <header className="header">
        <h1>📋 Deal Grid</h1>
        <button onClick={loadDeals} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="controls">
        <input
          type="text"
          placeholder="Search deals..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="search-input"
        />
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="status-filter"
        >
          <option value="all_not_deleted">All Active</option>
          <option value="open">Open</option>
          <option value="won">Won</option>
          <option value="lost">Lost</option>
        </select>
        <div className="count-badge">{filteredDeals.length} deals</div>
      </div>

      <div className="table-container">
        <table className="deals-table">
          <thead>
            <tr>
              <th onClick={() => handleSort('title')} className="sortable">
                Deal <SortIcon field="title" />
              </th>
              <th onClick={() => handleSort('value')} className="sortable">
                Value <SortIcon field="value" />
              </th>
              <th>Contact</th>
              <th>Organization</th>
              <th>Owner</th>
              <th>Status</th>
              <th onClick={() => handleSort('add_time')} className="sortable">
                Created <SortIcon field="add_time" />
              </th>
              <th onClick={() => handleSort('expected_close_date')} className="sortable">
                Expected Close <SortIcon field="expected_close_date" />
              </th>
            </tr>
          </thead>
          <tbody>
            {filteredDeals.map(deal => (
              <tr key={deal.id} className="deal-row">
                <td className="deal-title">{deal.title}</td>
                <td className="deal-value">{formatCurrency(deal.value, deal.currency)}</td>
                <td>{deal.person_name || '—'}</td>
                <td>{deal.org_name || '—'}</td>
                <td>{deal.owner_name || '—'}</td>
                <td>
                  <span className={`status-badge ${deal.status}`}>{deal.status}</span>
                </td>
                <td>{formatDate(deal.add_time)}</td>
                <td>{formatDate(deal.expected_close_date || '')}</td>
              </tr>
            ))}
          </tbody>
        </table>
        {filteredDeals.length === 0 && (
          <div className="empty-state">No deals found</div>
        )}
      </div>
    </div>
  );
}

export default App;
