import { createClient } from "@/lib/supabase/server";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Building2, Users, Stethoscope } from "lucide-react";
import { ClinicSettingsForm } from "@/components/settings/clinic-settings-form";
import { UsersList } from "@/components/settings/users-list";
import { ServicesCatalog } from "@/components/settings/services-catalog";

export const dynamic = "force-dynamic";

export default async function SettingsPage() {
  const supabase = await createClient();

  const { data: { user } } = await supabase.auth.getUser();
  const { data: profile } = await supabase.from("users").select("*, clinic:clinics(*)").eq("id", user?.id).single();
  const { data: users } = await supabase.from("users").select("*").order("created_at");
  const { data: services } = await supabase.from("services_catalog").select("*").order("name");

  const clinic = (profile as any)?.clinic;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Configuracion</h1>
        <p className="text-muted-foreground">Administra tu clinica, equipo y catalogo de servicios.</p>
      </div>

      <Tabs defaultValue="clinic">
        <TabsList>
          <TabsTrigger value="clinic" className="gap-2"><Building2 className="h-4 w-4" /> Clinica</TabsTrigger>
          <TabsTrigger value="users" className="gap-2"><Users className="h-4 w-4" /> Equipo</TabsTrigger>
          <TabsTrigger value="services" className="gap-2"><Stethoscope className="h-4 w-4" /> Servicios</TabsTrigger>
        </TabsList>

        <TabsContent value="clinic" className="mt-4">
          <ClinicSettingsForm clinic={clinic} />
        </TabsContent>
        <TabsContent value="users" className="mt-4">
          <UsersList users={users || []} currentUserId={user?.id || ""} />
        </TabsContent>
        <TabsContent value="services" className="mt-4">
          <ServicesCatalog services={services || []} />
        </TabsContent>
      </Tabs>
    </div>
  );
}
