import { redirect } from "next/navigation";
import { CalendarDays, Clock3, Database, Settings, Users } from "lucide-react";
import { isLocalAdmin } from "@/lib/admin-auth";
import { services } from "@/lib/data";
import { isSupabaseConfigured } from "@/lib/supabase/server";
import { logout } from "../actions";
import { readBookings, type Appointment } from "@/lib/local-bookings";
import { createAdminClient } from "@/lib/supabase/admin";
import { changeStatus } from "./actions";
import { AdminRefresh } from "@/components/admin-refresh";
import { GalleryManager } from "@/components/gallery-manager";
import { AppointmentList } from "@/components/appointment-list";

export const metadata={title:"Studio Dashboard",robots:{index:false,follow:false}};
export const dynamic="force-dynamic";

export default async function LocalAdmin(){
  if(!await isLocalAdmin())redirect("/admin/login");
  const connected=isSupabaseConfigured();
  let appointments:Appointment[];
  if(connected){const {data,error}=await createAdminClient().from("appointments").select("*, services(name)").order("created_at",{ascending:false});if(error)throw new Error("Appointments could not be loaded.");appointments=(data||[]).map(a=>({...a,service_name:a.services?.name||"Nail service"}));}
  else appointments=(await readBookings()).sort((a,b)=>b.created_at.localeCompare(a.created_at));
  const requested=appointments.filter(a=>a.status==="requested").length;
  const upcoming=appointments.filter(a=>["requested","confirmed"].includes(a.status)&&new Date(`${a.appointment_date}T${a.start_time}`)>=new Date()).length;
  const customers=new Set(appointments.map(a=>a.customer_email.toLowerCase())).size;
  return <section className="min-h-[75vh] bg-[#f7f1ed] px-4 py-8 sm:px-8"><div className="mx-auto max-w-7xl">
    <header className="flex flex-wrap items-center justify-between gap-4"><div><p className="eyebrow">Private studio workspace</p><h1 className="mt-2 font-serif text-4xl">Good day, Ella.</h1></div><form action={logout}><button className="btn-light">Sign out</button></form></header>
    <div className="mt-8 grid gap-4 sm:grid-cols-3">{[[CalendarDays,"Upcoming",upcoming],[Clock3,"Requests",requested],[Users,"Customers",customers]].map(([Icon,label,value])=>{const I=Icon as typeof Users;return <div key={String(label)} className="card flex items-center gap-4 p-5"><div className="grid h-11 w-11 place-items-center rounded-full bg-blush/50"><I size={19}/></div><div><p className="text-sm text-ink/45">{String(label)}</p><p className="font-serif text-3xl">{String(value)}</p></div></div>})}</div>
    <AppointmentList appointments={appointments}/>
    {!process.env.SMTP_PASSWORD&&!process.env.RESEND_API_KEY&&<p className="mt-3 text-sm text-ink/60">Email alerts to hello@nailsbyella.com are awaiting the mailbox password in the server settings. New bookings still appear here.</p>}
    <GalleryManager/>
    <div className="mt-8 grid gap-8 lg:grid-cols-[1.35fr_.65fr]">
      <section className="card p-6 sm:p-8"><div className="flex items-center gap-3"><Settings className="text-rose"/><h2 className="font-serif text-2xl">Current services</h2></div><div className="mt-6 grid gap-3 sm:grid-cols-2">{services.map(service=><div key={service.id} className="rounded-2xl bg-cream p-4"><p className="eyebrow">{service.category}</p><p className="mt-2 font-semibold">{service.name}</p></div>)}</div></section>
      <section className="card p-6 sm:p-8"><div className="flex items-center gap-3"><Database className="text-rose"/><h2 className="font-serif text-2xl">Saved requests</h2></div><p className="mt-5 leading-7 text-ink/60">{connected?"Appointments are saved to your connected database.":"Appointments are saved on this computer and remain available when the website restarts. Connect the production database before moving the website to online hosting."}</p></section>
    </div>
  </div></section>;
}
