// src/app/admin/(dashboard)/dashboard/skins/page.tsx

'use client';

import { useEffect, useState } from 'react';
import { Skin, useSkinStore } from '@/store/skinStore';
import { Loader2, Sun, Moon } from 'lucide-react';
import toast from 'react-hot-toast';
import { getApiErrorMessage } from '@/lib/utils/apiError';

export default function SkinsPage() {
  const { 
    currentSkin, 
    currentMode, 
    allSkins, 
    loading,
    fetchSkins,
    applySkin,
    toggleMode,
    saveEmployeePreference
  } = useSkinStore();

  const [isApplying, setIsApplying] = useState(false);

  useEffect(() => {
    fetchSkins();
  }, []);

  const handleApplySkin = async (skin: Skin) => {
    setIsApplying(true);
    try {
      applySkin(skin, currentMode);
      await saveEmployeePreference(skin.id, currentMode);
      toast.success(`${skin.name} applied successfully!`);
    } catch (error) {
        console.log('Error toggling mode:', error);
      toast.error(getApiErrorMessage(error, 'Failed to apply skin'));
    } finally {
      setIsApplying(false);
    }
  };

  const handleToggleMode = async () => {
    const newMode = currentMode === 'light' ? 'dark' : 'light';
    const skin = currentSkin;
    
    if (!skin) {
      toast.error('No skin selected');
      return;
    }

    try {
      toggleMode();
      await saveEmployeePreference(skin.id, newMode);
      toast.success(`Switched to ${newMode} mode`);
    } catch (error) {
        console.log('Error toggling mode:', error);
      toast.error(getApiErrorMessage(error, 'Failed to switch mode'));
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 size={32} className="animate-spin" style={{ color: 'var(--color-cta)' }} />
      </div>
    );
  }

  return (
    <div className="p-6 max-w-6xl mx-auto">
      {/* Header */}
      <div className="flex flex-wrap justify-between items-center gap-3 mb-8">
        <div>
          <h1 className="text-2xl font-semibold" style={{ color: 'var(--color-text)' }}>
            Theme Skins
          </h1>
          <p className="text-sm mt-1" style={{ color: 'var(--color-text-secondary)' }}>
            Choose a skin to customize the dashboard appearance
          </p>
        </div>

        {/* Mode Toggle */}
        <button
          onClick={handleToggleMode}
          className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all hover:opacity-80"
          style={{
            background: currentMode === 'dark' ? 'var(--color-surface-alt)' : 'var(--color-cta-light)',
            color: currentMode === 'dark' ? 'var(--color-text)' : 'var(--color-cta)',
            border: '1px solid var(--color-border)',
          }}
        >
          {currentMode === 'light' ? <Moon size={16} /> : <Sun size={16} />}
          {currentMode === 'light' ? 'Switch to Dark' : 'Switch to Light'}
        </button>
      </div>

      {/* Active Skin Badge */}
      <div className="mb-6 p-3 rounded-lg" style={{
        background: 'var(--color-surface)',
        border: '1px solid var(--color-border)',
      }}>
        <div className="flex items-center gap-3">
          <div className="flex gap-1">
            <div 
              className="w-8 h-8 rounded-full border-2 border-border"
              style={{ background: currentSkin?.light_color_cta }}
            />
            <div 
              className="w-8 h-8 rounded-full border-2 border-border"
              style={{ background: currentSkin?.light_color_background }}
            />
            <div 
              className="w-8 h-8 rounded-full border-2 border-border"
              style={{ background: currentSkin?.light_color_text }}
            />
          </div>
          <div>
            <span className="font-medium" style={{ color: 'var(--color-text)' }}>
              Active: {currentSkin?.name}
            </span>
            <span className="text-sm ml-2" style={{ color: 'var(--color-text-tertiary)' }}>
              ({currentMode} mode)
            </span>
          </div>
          <span className="text-xs px-2 py-1 rounded-full ml-auto" style={{
            background: 'var(--color-success-light)',
            color: 'var(--color-success)',
          }}>
            ✓ Applied
          </span>
        </div>
      </div>

      {/* Skin Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
        {allSkins.filter(s => s.is_active).map((skin) => {
          const isActive = currentSkin?.id === skin.id;

          return (
            <div
              key={skin.id}
              className={`rounded-lg border-2 p-4 transition-all ${
                isActive 
                  ? 'border-cta ring-2 ring-cta/20' 
                  : 'border-border hover:border-cta/50 hover:shadow-lg'
              }`}
              style={{
                background: 'var(--color-surface)',
                boxShadow: isActive ? 'var(--shadow-card-md)' : 'var(--shadow-card-sm)',
              }}
            >
              {/* Color Preview */}
              <div className="aspect-video rounded-lg overflow-hidden mb-3 grid grid-cols-4 gap-0.5 p-0.5" style={{
                background: 'var(--color-border)',
              }}>
                <div style={{ background: skin.light_color_cta }} />
                <div style={{ background: skin.light_color_surface }} />
                <div style={{ background: skin.light_color_text }} />
                <div style={{ background: skin.light_color_sidebar }} />
                <div style={{ background: skin.light_color_background }} />
                <div style={{ background: skin.light_color_success }} />
                <div style={{ background: skin.light_color_danger }} />
                <div style={{ background: skin.light_color_info }} />
              </div>

              {/* Info */}
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <h3 className="font-medium" style={{ color: 'var(--color-text)' }}>
                    {skin.name}
                  </h3>
                  <p className="text-xs capitalize" style={{ color: 'var(--color-text-tertiary)' }}>
                    {skin.category}
                  </p>
                  <div className="flex items-center gap-2 mt-1">
                    {skin.is_default && (
                      <span className="text-[10px] px-1.5 py-0.5 rounded" style={{
                        background: 'var(--color-cta-light)',
                        color: 'var(--color-cta)',
                      }}>
                        Default
                      </span>
                    )}
                    {isActive && (
                      <span className="text-[10px] px-1.5 py-0.5 rounded" style={{
                        background: 'var(--color-success-light)',
                        color: 'var(--color-success)',
                      }}>
                        Active
                      </span>
                    )}
                  </div>
                </div>

                <button
                  onClick={() => handleApplySkin(skin)}
                  disabled={isApplying || isActive}
                  className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-all shrink-0 ${
                    isActive 
                      ? 'bg-green-500 text-white cursor-default' 
                      : 'hover:opacity-80'
                  }`}
                  style={{
                    background: isActive ? 'var(--color-success)' : 'var(--color-cta)',
                    color: 'white',
                  }}
                >
                  {isApplying ? 'Applying...' : isActive ? '✓ Active' : 'Apply'}
                </button>
              </div>
            </div>
          );
        })}
      </div>

      {/* Preview Section */}
      <div className="mt-8 p-6 rounded-lg" style={{
        background: 'var(--color-surface)',
        border: '1px solid var(--color-border)',
      }}>
        <h3 className="font-medium mb-4" style={{ color: 'var(--color-text)' }}>
          Live Preview
        </h3>
        <div className="space-y-4">
          <div className="flex flex-wrap gap-3">
            <button className="px-4 py-2 rounded-lg text-sm font-medium" style={{
              background: 'var(--color-cta)',
              color: 'white',
            }}>
              Primary Button
            </button>
            <button className="px-4 py-2 rounded-lg text-sm font-medium" style={{
              background: 'var(--color-success)',
              color: 'white',
            }}>
              Success
            </button>
            <button className="px-4 py-2 rounded-lg text-sm font-medium" style={{
              background: 'var(--color-danger)',
              color: 'white',
            }}>
              Danger
            </button>
            <button className="px-4 py-2 rounded-lg text-sm font-medium" style={{
              background: 'var(--color-info)',
              color: 'white',
            }}>
              Info
            </button>
            <button className="px-4 py-2 rounded-lg text-sm font-medium" style={{
              background: 'var(--color-warning)',
              color: 'white',
            }}>
              Warning
            </button>
          </div>
          <div className="p-4 rounded-lg" style={{
            background: 'var(--color-surface-alt)',
            border: '1px solid var(--color-border)',
          }}>
            <p style={{ color: 'var(--color-text)' }}>Sample text content</p>
            <p className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>
              Secondary text for preview purposes
            </p>
          </div>
          <div className="flex gap-4">
            <div className="flex-1 p-4 rounded-lg" style={{
              background: 'var(--color-surface)',
              border: '1px solid var(--color-border)',
            }}>
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-full" style={{ background: 'var(--color-cta)' }} />
                <div>
                  <div className="h-3 w-24 rounded" style={{ background: 'var(--color-text)' }} />
                  <div className="h-2 w-16 rounded mt-1" style={{ background: 'var(--color-text-tertiary)' }} />
                </div>
              </div>
            </div>
            <div className="flex-1 p-4 rounded-lg" style={{
              background: 'var(--color-surface)',
              border: '1px solid var(--color-border)',
            }}>
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-full" style={{ background: 'var(--color-cta-hover)' }} />
                <div>
                  <div className="h-3 w-24 rounded" style={{ background: 'var(--color-text-secondary)' }} />
                  <div className="h-2 w-16 rounded mt-1" style={{ background: 'var(--color-text-muted)' }} />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}