import React, { useState, useMemo, useTransition, useCallback, useEffect } from 'react';

function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);

  return debouncedValue;
}

type Toast = { id: number; message: string; type: 'success' | 'error' };

function useToast() {
  const [toasts, setToasts] = useState<Toast[]>([]);

  const showToast = useCallback((message: string, type: 'success' | 'error' = 'success') => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000);
  }, []);

  return { toasts, showToast };
}

const mockData = [
  {
    "id": "t1",
    "name": "Dawn",
    "version": "2.0",
    "author": "Shopify",
    "modified": "2024-02-10",
    "status": "active"
  },
  {
    "id": "t2",
    "name": "Brooklyn",
    "version": "1.5",
    "author": "Shopify",
    "modified": "2024-01-15",
    "status": "draft"
  },
  {
    "id": "t3",
    "name": "Debut",
    "version": "3.0",
    "author": "Shopify",
    "modified": "2024-02-08",
    "status": "draft"
  },
  {
    "id": "t4",
    "name": "Custom Theme",
    "version": "1.0",
    "author": "Custom",
    "modified": "2024-02-12",
    "status": "draft"
  }
];

export default function App() {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'draft'>('all');
  const [isPending, startTransition] = useTransition();
  const { toasts, showToast } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredData = useMemo(() => {
    return mockData.filter((item: any) => {
      const searchField = Object.values(item).join(' ').toLowerCase();
      const matchesSearch = searchField.includes(debouncedSearch.toLowerCase());
      const matchesStatus = statusFilter === 'all' || item.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => ({
    total: mockData.length,
    active: mockData.filter((i: any) => i.status === 'active').length,
    value1: Math.floor(Math.random() * 1000),
    value2: Math.floor(Math.random() * 100),
  }), []);

  const handleSearch = (value: string) => {
    startTransition(() => setSearchQuery(value));
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Theme Editor</h1>
        <p>Customize store themes</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Themes</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active</div>
          <div className="stat-value">{stats.active}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Assets</div>
          <div className="stat-value">{stats.value1}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Modified</div>
          <div className="stat-value">{stats.value2}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          placeholder="Search themes..."
          value={searchQuery}
          onChange={(e) => handleSearch(e.target.value)}
          className="search-input"
        />
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value as any)}
          className="filter-select"
        >
          <option value="all">All Status</option>
          <option value="active">Active</option>
          <option value="draft">Draft</option>
        </select>
      </div>

      {filteredData.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">🎨</div>
          <h3>No data found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className="data-grid" style={{ opacity: isPending ? 0.6 : 1 }}>
          {filteredData.map((item: any) => (
            <div key={item.id} className="data-card">
              <h3>{Object.values(item)[1] as string}</h3>
              <p>{Object.values(item)[2] as string}</p>
              <div style={{ marginTop: '1rem' }}>
                <span className={`status-badge status-${item.status}`}>
                  {item.status}
                </span>
              </div>
            </div>
          ))}
        </div>
      )}

      <div className="toast-container">
        {toasts.map(toast => (
          <div key={toast.id} className={`toast toast-${toast.type}`}>
            {toast.message}
          </div>
        ))}
      </div>
    </div>
  );
}