import { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Save } from 'lucide-react';
import { DashboardNote } from './DashboardNote';
import { RoleDashboardSection } from './RoleDashboardSection';
import { toast } from 'sonner';

export type Role = 'Initiator' | 'Approver' | 'Spectator';

export type KPICard = 
  | 'Total Requests'
  | 'Open Requests'
  | 'Approved Requests'
  | 'Rejected Requests'
  | 'My Pending Actions'
  | 'TAT Compliance'
  | 'Delayed Workflows'
  | 'Average Cycle Time';

interface DashboardConfigData {
  [key: string]: {
    [kpi: string]: boolean;
  };
}

export function DashboardConfig() {
  const [config, setConfig] = useState<DashboardConfigData>({
    Initiator: {
      'Total Requests': true,
      'Open Requests': true,
      'Approved Requests': true,
      'Rejected Requests': true,
      'My Pending Actions': true,
      'TAT Compliance': true,
      'Delayed Workflows': true,
      'Average Cycle Time': true
    },
    Approver: {
      'Total Requests': true,
      'Open Requests': true,
      'Approved Requests': true,
      'Rejected Requests': true,
      'My Pending Actions': true,
      'TAT Compliance': true,
      'Delayed Workflows': true,
      'Average Cycle Time': true
    },
    Spectator: {
      'Total Requests': true,
      'Open Requests': true,
      'Approved Requests': true,
      'Rejected Requests': true,
      'My Pending Actions': true,
      'TAT Compliance': true,
      'Delayed Workflows': true,
      'Average Cycle Time': true
    }
  });

  const handleSave = () => {
    // TODO: Implement API call to save dashboard configuration
    toast.success('Dashboard layout saved successfully');
  };

  const handleKPIToggle = (role: Role, kpi: KPICard, checked: boolean) => {
    setConfig(prev => ({
      ...prev,
      [role]: {
        ...prev[role],
        [kpi]: checked
      }
    }));
  };

  const roles: Role[] = ['Initiator', 'Approver', 'Spectator'];

  return (
    <Card>
      <CardHeader>
        <CardTitle>Dashboard Layout Configuration</CardTitle>
        <CardDescription>
          Control which KPI cards are visible for each user role
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <DashboardNote />

        <div className="space-y-6">
          {roles.map((role) => (
            <RoleDashboardSection
              key={role}
              role={role}
              kpis={config[role] || {}}
              onKPIToggle={(kpi, checked) => handleKPIToggle(role, kpi, checked)}
            />
          ))}
        </div>

        <Button onClick={handleSave} className="bg-re-green hover:bg-re-green/90">
          <Save className="w-4 h-4 mr-2" />
          Save Dashboard Layout
        </Button>
      </CardContent>
    </Card>
  );
}

