// TicketList - Extracted ticket display logic from TicketsPanel
import React, { useState } from 'react';
import TicketCard from './TicketCard';

// TableExport component for ticket data export
function TableExport({ data, filename, title }) {
  const [showMenu, setShowMenu] = useState(false);

  const convertToCSV = (data) => {
    if (!data || data.length === 0) return '';
    
    const headers = Object.keys(data[0]);
    const csvHeaders = headers.join(',');
    
    const csvRows = data.map(row => {
      return headers.map(header => {
        const value = row[header];
        if (typeof value === 'object' && value !== null) {
          return `"${JSON.stringify(value).replaceAll('"', '""')}"`;
        }
        if (typeof value === 'string' && (value.includes(',') || value.includes('"') || value.includes('\n') || value.includes('\r'))) {
          return `"${value.replaceAll('"', '""')}"`;
        }
        return value ?? '';
      }).join(',');
    });
    
    return [csvHeaders, ...csvRows].join('\n');
  };

  const downloadCSV = () => {
    const csv = convertToCSV(data);
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `${filename}.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  const downloadJSON = () => {
    const json = JSON.stringify(data, null, 2);
    const blob = new Blob([json], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `${filename}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  return (
    <div className="relative">
      <button
        onClick={() => setShowMenu(!showMenu)}
        className="px-3 py-1 text-sm bg-gray-100 hover:bg-gray-200 rounded border"
      >
        Export {title}
      </button>
      
      {showMenu && (
        <div className="absolute right-0 mt-1 w-48 bg-white rounded-md shadow-lg border z-10">
          <div className="py-1">
            <button
              onClick={downloadCSV}
              className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
            >
              Download CSV
            </button>
            <button
              onClick={downloadJSON}
              className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
            >
              Download JSON
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function TicketList({ 
  filtered, 
  selectedTicket, 
  setSelectedTicket,
  selectedTickets,
  toggleTicketSelection,
  handleRefresh,
  visibleSprints 
}) {
  const [view, setView] = useState("list"); // list | board

  if (filtered.length === 0) {
    return (
      <div className="bg-white rounded-lg border p-8 text-center">
        <div className="text-gray-400 text-4xl mb-4">📋</div>
        <h3 className="text-lg font-medium text-gray-900 mb-2">No tickets found</h3>
        <p className="text-gray-500">Try adjusting your filters or create a new ticket.</p>
      </div>
    );
  }

  if (view === "board") {
    // Kanban board view - simplified for this extraction
    const TICKET_STATUSES = ["backlog", "todo", "in_progress", "in_review", "done", "cancelled"];
    const STATUS_COLORS = {
      backlog: "bg-gray-100 text-gray-600",
      todo: "bg-blue-100 text-blue-700",
      in_progress: "bg-amber-100 text-amber-700",
      in_review: "bg-purple-100 text-purple-700",
      done: "bg-emerald-100 text-emerald-700",
      cancelled: "bg-red-100 text-red-600",
    };

    const boardColumns = {};
    TICKET_STATUSES.forEach(s => { boardColumns[s] = []; });
    filtered.forEach(t => { if (boardColumns[t.status]) boardColumns[t.status].push(t); });

    return (
      <div className="space-y-4">
        {/* View toggle */}
        <div className="flex justify-between items-center">
          <h3 className="text-sm font-medium text-gray-900">Kanban Board</h3>
          <button
            onClick={() => setView("list")}
            className="text-xs text-gray-500 hover:text-gray-700"
          >
            Switch to List View
          </button>
        </div>

        {/* Board columns */}
        <div className="grid grid-cols-6 gap-4">
          {TICKET_STATUSES.map(status => (
            <div key={status} className="bg-gray-50 rounded-lg p-3">
              <div className={`text-xs font-medium px-2 py-1 rounded mb-3 ${STATUS_COLORS[status]}`}>
                {status} ({boardColumns[status].length})
              </div>
              <div className="space-y-2">
                {boardColumns[status].map(ticket => (
                  <div key={ticket.id} className="bg-white p-2 rounded border text-xs">
                    <div className="font-medium truncate">{ticket.title || ticket.task}</div>
                    <div className="text-gray-500 truncate">{ticket.id}</div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* View toggle and export */}
      <div className="flex justify-between items-center">
        <h3 className="text-sm font-medium text-gray-900">Ticket List ({filtered.length})</h3>
        <div className="flex items-center space-x-2">
          <TableExport 
            data={filtered.map(t => ({
              id: t.id,
              title: t.title || t.task,
              status: t.status,
              priority: t.priority,
              type: t.type,
              assigned_tool: t.assigned_tool?.tool || '',
              created_at: new Date(t.created_at * 1000).toISOString(),
              updated_at: new Date(t.updated_at * 1000).toISOString()
            }))}
            filename="tickets"
            title="Tickets"
          />
          <button
            onClick={() => setView("board")}
            className="text-xs text-gray-500 hover:text-gray-700"
          >
            Switch to Board View
          </button>
        </div>
      </div>

      {/* Ticket cards */}
      <div className="space-y-3">
        {filtered.map(ticket => (
          <TicketCard 
            key={ticket.id} 
            ticket={ticket} 
            onUpdate={handleRefresh} 
            sprints={visibleSprints}
            isSelected={selectedTicket === ticket.id}
            onSelect={setSelectedTicket}
            isBulkMode={selectedTickets.size > 0}
            isChecked={selectedTickets.has(ticket.id)}
            onToggleCheck={toggleTicketSelection}
          />
        ))}
      </div>
    </div>
  );
}

export default TicketList;
