'use client';

import { useState, useEffect } from 'react';

export interface DashboardTile {
  id: string;
  component: string;
  title: string;
  visible: boolean;
  order: number;
}

export function useDashboardLayout(role: string) {
  const storageKey = `dashboard-layout-${role}`;
  
  const [tiles, setTiles] = useState<DashboardTile[]>(() => {
    if (typeof window === 'undefined') return [];
    const saved = localStorage.getItem(storageKey);
    return saved ? JSON.parse(saved) : getDefaultTiles(role);
  });

  useEffect(() => {
    if (typeof window !== 'undefined') {
      localStorage.setItem(storageKey, JSON.stringify(tiles));
    }
  }, [tiles, storageKey]);

  const updateTiles = (newTiles: DashboardTile[]) => {
    setTiles(newTiles.map((tile, index) => ({ ...tile, order: index })));
  };

  return { tiles, updateTiles };
}

function getDefaultTiles(role: string): DashboardTile[] {
  const roleTiles: Record<string, DashboardTile[]> = {
    technical: [
      { id: 'system-health', component: 'SystemHealthTile', title: 'System Health', visible: true, order: 0 },
      { id: 'integrations', component: 'IntegrationStatusTile', title: 'Integrations', visible: true, order: 1 },
      { id: 'pipelines', component: 'DataPipelineTile', title: 'Data Pipelines', visible: true, order: 2 },
      { id: 'resources', component: 'ResourceUtilizationTile', title: 'Resource Utilization', visible: true, order: 3 },
    ],
    business: [
      { id: 'cost', component: 'CostOverviewTile', title: 'Cost Overview', visible: true, order: 0 },
      { id: 'usage', component: 'ResourceUsageTile', title: 'Resource Usage', visible: true, order: 1 },
      { id: 'billing', component: 'BillingTile', title: 'Billing', visible: true, order: 2 },
      { id: 'compliance', component: 'ComplianceStatusTile', title: 'Compliance', visible: true, order: 3 },
    ],
    developer: [
      { id: 'api-usage', component: 'APIUsageTile', title: 'API Usage', visible: true, order: 0 },
      { id: 'deployments', component: 'DeploymentsTile', title: 'Deployments', visible: true, order: 1 },
      { id: 'environments', component: 'TestEnvironmentsTile', title: 'Test Environments', visible: true, order: 2 },
      { id: 'api-keys', component: 'APIKeysTile', title: 'API Keys', visible: true, order: 3 },
    ],
  };

  return roleTiles[role] || roleTiles.technical;
}

