import React, { useState, useEffect } from 'react';
import { Trash2, RefreshCw } from 'lucide-react';
import { ActionEntry } from '../types';
import { Button } from '../components/ui/button';
import { ThemeProvider } from '../contexts/ThemeContext';

const ActionsContent: React.FC = () => {
  const [actions, setActions] = useState<ActionEntry[]>([]);
  const [selectedAction, setSelectedAction] = useState<ActionEntry | null>(null);
  const [loading, setLoading] = useState(true);

  const loadActions = async () => {
    try {
      const allActions = await window.actionsAPI.getAll();
      setActions(allActions);

      if (allActions.length > 0 && !selectedAction) {
        setSelectedAction(allActions[0]);
      }
    } catch (error) {
      console.error('Failed to load actions:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadActions();

    // Listen for new actions
    const cleanup = window.actionsAPI.onActionAdded((action) => {
      setActions(prev => [action, ...prev]);
      if (!selectedAction) {
        setSelectedAction(action);
      }
    });

    return cleanup;
  }, []);

  const handleDelete = async (id: string) => {
    try {
      await window.actionsAPI.delete(id);
      setActions(prev => prev.filter(a => a.id !== id));

      if (selectedAction?.id === id) {
        setSelectedAction(actions.length > 1 ? actions[0] : null);
      }
    } catch (error) {
      console.error('Failed to delete action:', error);
    }
  };

  const handleClearAll = async () => {
    if (confirm('Are you sure you want to clear all actions?')) {
      try {
        await window.actionsAPI.clear();
        setActions([]);
        setSelectedAction(null);
      } catch (error) {
        console.error('Failed to clear actions:', error);
      }
    }
  };

  const formatTimestamp = (timestamp: number) => {
    const date = new Date(timestamp);
    return date.toLocaleString();
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return 'text-green-600';
      case 'failed':
        return 'text-red-600';
      case 'running':
        return 'text-blue-600';
      default:
        return 'text-gray-600';
    }
  };

  return (
    <div className="h-screen w-screen flex flex-col overflow-hidden bg-background">

      {/* Header */}
      <div
        className="border-b border-border bg-secondary px-6 flex items-center justify-center relative h-[52px]"
        style={{
          WebkitAppRegion: 'drag'
        } as React.CSSProperties}
      >
        <h1
          className="text-base font-semibold text-foreground select-none"
          style={{
            WebkitAppRegion: 'no-drag'
          } as React.CSSProperties}
        >
          Actions
        </h1>
        <div
          className="absolute right-6"
          style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
        >
          <Button
            onClick={handleClearAll}
            variant="ghost"
            size="sm"
            disabled={actions.length === 0}
            className="text-foreground hover:bg-accent"
          >
            <Trash2 className="h-4 w-4 mr-2" />
            Clear All
          </Button>
        </div>
      </div>

      {/* Main Content */}
      <div className="flex-1 flex overflow-hidden">
        {/* Sidebar */}
        <div className="w-80 border-r border-border bg-secondary flex flex-col">
          <div className="px-4 py-4 border-b border-border">
            <div className="flex items-center justify-between">
              <p className="text-sm font-semibold text-foreground">
                {actions.length} {actions.length === 1 ? 'Action' : 'Actions'}
              </p>
              <Button
                onClick={loadActions}
                variant="ghost"
                size="sm"
                className="text-foreground hover:bg-accent"
              >
                <RefreshCw className="h-4 w-4" />
              </Button>
            </div>
          </div>

          <div className="flex-1 overflow-auto">
            {loading ? (
              <div className="flex items-center justify-center py-8">
                <div className="inline-block h-6 w-6 animate-spin rounded-full border-4 border-solid border-blue-600 border-r-transparent"></div>
              </div>
            ) : actions.length === 0 ? (
              <div className="p-6 text-center text-sm text-muted-foreground">
                No actions triggered yet.
              </div>
            ) : (
              <div className="divide-y divide-border">
                {actions.map((action) => (
                  <button
                    key={action.id}
                    onClick={() => setSelectedAction(action)}
                    className={`w-full px-4 py-3 text-left transition-colors hover:bg-accent ${
                      selectedAction?.id === action.id ? 'bg-accent' : ''
                    }`}
                  >
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-xs text-muted-foreground">
                        {formatTimestamp(action.timestamp)}
                      </span>
                      <span className={`text-xs font-medium ${getStatusColor(action.status)}`}>
                        {action.status}
                      </span>
                    </div>
                    <div className="text-sm font-medium truncate text-foreground">
                      {action.url}
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Detail Panel */}
        <div className="flex-1 overflow-auto bg-background">
          {selectedAction ? (
            <div className="p-6 space-y-4 max-w-4xl">
              <div className="rounded-lg border border-border bg-card p-5">
                <div className="flex items-center justify-between mb-4">
                  <h2 className="text-base font-semibold text-foreground">
                    Action Details
                  </h2>
                  <Button
                    onClick={() => handleDelete(selectedAction.id)}
                    variant="ghost"
                    size="sm"
                  >
                    <Trash2 className="h-4 w-4 mr-2" />
                    Delete
                  </Button>
                </div>

                <div className="space-y-3">
                  <div>
                    <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                      URL
                    </label>
                    <div className="mt-1 p-3 rounded border border-border bg-background text-sm font-mono break-all text-foreground">
                      {selectedAction.url}
                    </div>
                  </div>

                  <div>
                    <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                      Triggered At
                    </label>
                    <div className="mt-1 text-sm text-foreground">
                      {formatTimestamp(selectedAction.timestamp)}
                    </div>
                  </div>

                  <div>
                    <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                      Status
                    </label>
                    <div className={`mt-1 text-sm font-medium ${getStatusColor(selectedAction.status)}`}>
                      {selectedAction.status.toUpperCase()}
                    </div>
                  </div>
                </div>
              </div>

              <div className="rounded-lg border border-border bg-card p-5">
                <h3 className="text-sm font-semibold mb-3 text-foreground">
                  Command Output
                </h3>
                <div className="bg-[#1e1e1e] rounded p-4 text-xs font-mono text-[#d4d4d4] min-h-[200px] max-h-[400px] overflow-auto">
                  {selectedAction.logs.length > 0 ? (
                    selectedAction.logs.map((log, index) => (
                      <div key={index} className="mb-1">
                        {log}
                      </div>
                    ))
                  ) : (
                    <div className="text-[#888]">No logs available</div>
                  )}
                </div>
              </div>
            </div>
          ) : (
            <div className="flex items-center justify-center h-full">
              <div className="text-center text-muted-foreground">
                <p className="text-sm">Select an action to view details</p>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const App: React.FC = () => {
  return (
    <ThemeProvider>
      <ActionsContent />
    </ThemeProvider>
  );
};

export default App;
