import { Settings } from 'lucide-react';
import type { SectionSettings } from '../api';
import { formatAmount } from '@/lib/format';
import { Card } from '@/components/ui/card';
import {
  Accordion,
  AccordionItem,
  AccordionTrigger,
  AccordionContent,
} from '@/components/ui/accordion';
import { getColorClasses } from '@/lib/colors';
import { cn } from '@/lib/utils';

interface Props {
  sectionId: string;
  settings: SectionSettings;
  total?: number;
  totalCurrency?: string;
  onToggleExpanded: (expanded: boolean) => void;
  onOpenConfig: () => void;
  children: React.ReactNode;
}

export default function DashboardSection({
  sectionId,
  settings,
  total,
  totalCurrency,
  onToggleExpanded,
  onOpenConfig,
  children,
}: Props) {
  const colors = getColorClasses(settings.color);

  return (
    <Card className={cn('relative overflow-hidden border-l-4', colors.borderLeft)}>
      {/* Settings icon — outside accordion trigger to avoid button-in-button */}
      <button
        onClick={onOpenConfig}
        className="absolute top-2.5 right-3 z-10 p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors cursor-pointer"
        title="Section settings"
        aria-label="Section settings"
      >
        <Settings className="w-3.5 h-3.5" />
      </button>

      <Accordion
        value={settings.expanded ? [sectionId] : []}
        onValueChange={(value: string[]) => onToggleExpanded(value.includes(sectionId))}
      >
        <AccordionItem value={sectionId} className="border-none">
          <AccordionTrigger
            className="px-4 py-3 hover:no-underline cursor-pointer"
            aria-label={`Expand ${settings.label}`}
          >
            <div className="flex items-center justify-between w-full pr-8">
              <span className="text-sm font-semibold text-foreground">
                {settings.label}
              </span>
              {total != null && totalCurrency && (
                <span data-sensitive className="text-sm font-bold font-mono text-foreground">
                  {formatAmount(total, totalCurrency)}
                </span>
              )}
            </div>
          </AccordionTrigger>
          <AccordionContent>
            <div className="divide-y divide-border mx-4 mb-4 rounded-lg overflow-hidden">
              {children}
            </div>
          </AccordionContent>
        </AccordionItem>
      </Accordion>
    </Card>
  );
}
