'use client';

import { useState, useEffect } from 'react';
import { Theme } from '@/types/theme';
import ThemeEditor from '@/components/ThemeEditor';

export default function ThemesPage() {
  const [themes, setThemes] = useState<Theme[]>([]);
  const [activeTheme, setActiveTheme] = useState<Theme | null>(null);
  const [editingTheme, setEditingTheme] = useState<Theme | undefined>();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchThemes();
  }, []);

  const fetchThemes = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/themes');
      if (!response.ok) throw new Error('Failed to fetch themes');
      const data = await response.json();
      setThemes(data);
      setActiveTheme(data.find((t: Theme) => t.is_active) || null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
    } finally {
      setLoading(false);
    }
  };

  const handleCreateTheme = async (themeData: Partial<Theme>) => {
    try {
      const response = await fetch('/api/themes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(themeData),
      });

      if (!response.ok) throw new Error('Failed to create theme');

      await fetchThemes();
      setEditingTheme(undefined);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create theme');
    }
  };

  const handleUpdateTheme = async (themeData: Partial<Theme>) => {
    if (!editingTheme) return;

    try {
      const response = await fetch(`/api/themes/${editingTheme.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(themeData),
      });

      if (!response.ok) throw new Error('Failed to update theme');

      await fetchThemes();
      setEditingTheme(undefined);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to update theme');
    }
  };

  const handleActivateTheme = async (themeId: string) => {
    try {
      const response = await fetch(`/api/themes/${themeId}/activate`, {
        method: 'POST',
      });

      if (!response.ok) throw new Error('Failed to activate theme');

      await fetchThemes();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to activate theme');
    }
  };

  const handleDeleteTheme = async (themeId: string) => {
    if (!confirm('Are you sure you want to delete this theme?')) return;

    try {
      const response = await fetch(`/api/themes/${themeId}`, {
        method: 'DELETE',
      });

      if (!response.ok) throw new Error('Failed to delete theme');

      await fetchThemes();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to delete theme');
    }
  };

  if (loading) return <div className="p-8">Loading themes...</div>;
  if (error) return <div className="p-8 text-red-600">Error: {error}</div>;

  return (
    <div className="p-8">
      <div className="flex justify-between items-center mb-8">
        <div>
          <h1 className="text-3xl font-bold">Theme Management</h1>
          <p className="text-gray-600 mt-2">Manage app themes and colors across all platforms</p>
        </div>
        <button
          onClick={() => setEditingTheme(undefined)}
          className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
        >
          Create New Theme
        </button>
      </div>

      {/* Active Theme Display */}
      {activeTheme && (
        <div className="bg-white rounded-lg border p-6 mb-8">
          <h2 className="text-xl font-semibold mb-4">Currently Active Theme</h2>
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-lg font-medium">{activeTheme.name}</h3>
              {activeTheme.description && (
                <p className="text-gray-600">{activeTheme.description}</p>
              )}
              <div className="flex gap-4 mt-2">
                <div className="flex items-center gap-2">
                  <div
                    className="w-4 h-4 rounded"
                    style={{ backgroundColor: activeTheme.desktop.primary }}
                  />
                  <span className="text-sm">Primary</span>
                </div>
                <div className="flex items-center gap-2">
                  <div
                    className="w-4 h-4 rounded"
                    style={{ backgroundColor: activeTheme.desktop.idle }}
                  />
                  <span className="text-sm">Idle</span>
                </div>
                <div className="flex items-center gap-2">
                  <div
                    className="w-4 h-4 rounded"
                    style={{ backgroundColor: activeTheme.desktop.listening }}
                  />
                  <span className="text-sm">Listening</span>
                </div>
              </div>
            </div>
            <div className="text-sm text-gray-500">
              Active since {new Date(activeTheme.updated_at).toLocaleDateString()}
            </div>
          </div>
        </div>
      )}

      {/* Themes List */}
      <div className="bg-white rounded-lg border">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 border-b">
              <tr>
                <th className="text-left p-4 font-medium">Theme</th>
                <th className="text-left p-4 font-medium">Description</th>
                <th className="text-left p-4 font-medium">Status</th>
                <th className="text-left p-4 font-medium">Updated</th>
                <th className="text-left p-4 font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {themes.map(theme => (
                <tr key={theme.id} className="border-b hover:bg-gray-50">
                  <td className="p-4">
                    <div className="flex items-center gap-3">
                      <div className="flex gap-1">
                        <div
                          className="w-6 h-6 rounded"
                          style={{ backgroundColor: theme.desktop.primary }}
                        />
                        <div
                          className="w-6 h-6 rounded"
                          style={{ backgroundColor: theme.desktop.idle }}
                        />
                        <div
                          className="w-6 h-6 rounded"
                          style={{ backgroundColor: theme.desktop.listening }}
                        />
                      </div>
                      <span className="font-medium">{theme.name}</span>
                    </div>
                  </td>
                  <td className="p-4 text-gray-600">{theme.description || '-'}</td>
                  <td className="p-4">
                    {theme.is_active ? (
                      <span className="px-2 py-1 bg-green-100 text-green-800 rounded-full text-sm">
                        Active
                      </span>
                    ) : theme.is_default ? (
                      <span className="px-2 py-1 bg-gray-100 text-gray-800 rounded-full text-sm">
                        Default
                      </span>
                    ) : (
                      <span className="px-2 py-1 bg-gray-100 text-gray-600 rounded-full text-sm">
                        Inactive
                      </span>
                    )}
                  </td>
                  <td className="p-4 text-gray-600">
                    {new Date(theme.updated_at).toLocaleDateString()}
                  </td>
                  <td className="p-4">
                    <div className="flex gap-2">
                      {!theme.is_active && (
                        <button
                          onClick={() => handleActivateTheme(theme.id)}
                          className="px-3 py-1 text-sm bg-green-500 text-white rounded hover:bg-green-600"
                        >
                          Activate
                        </button>
                      )}
                      <button
                        onClick={() => setEditingTheme(theme)}
                        className="px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600"
                      >
                        Edit
                      </button>
                      {!theme.is_default && (
                        <button
                          onClick={() => handleDeleteTheme(theme.id)}
                          className="px-3 py-1 text-sm bg-red-500 text-white rounded hover:bg-red-600"
                        >
                          Delete
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Theme Editor Modal */}
      {editingTheme !== undefined && (
        <ThemeEditor
          theme={editingTheme}
          onSave={editingTheme ? handleUpdateTheme : handleCreateTheme}
          onCancel={() => setEditingTheme(undefined)}
        />
      )}
    </div>
  );
}
