import Link from "next/link";
import { requireAccount, getSession } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { formatNumber, timeAgo } from "@/lib/utils";
import { Card, CardBody, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { ThemeToggle } from "@/components/theme-toggle";
import { Search, Bell, MessageSquare, ChevronDown, Eye, Pencil, UserCircle } from "lucide-react";
import { MiniChart, TrendChart, DonutChart, SegmentsChart } from "./dashboard-charts";
import { format } from "date-fns";

export const dynamic = "force-dynamic";

export default async function DashboardPage() {
  const membership = await requireAccount();
  const session = await getSession();
  const accountId = membership.account.id;

  const [
    openConvs,
    totalConvs,
    recentChats,
    templates,
    agents
  ] = await Promise.all([
    prisma.conversation.count({ where: { accountId, status: "OPEN" } }),
    prisma.conversation.count({ where: { accountId } }),
    prisma.conversation.findMany({
      where: { accountId },
      orderBy: { lastMessageAt: "desc" },
      take: 3,
      include: { contact: true, assignee: true },
    }),
    prisma.messageTemplate.findMany({
      where: { accountId },
      take: 2,
    }),
    prisma.user.findMany({
      take: 3,
      where: { memberships: { some: { accountId } } }
    }),
  ]);

  const activeChats = openConvs;
  const totalChats = totalConvs;

  return (
    <div className="-m-4 sm:-m-6 lg:-m-8 min-h-full bg-gradient-to-br from-[#d4e4db] via-[#e5efe9] to-[#f4f7f5] p-6 lg:p-8 text-slate-900 font-sans">
      
      {/* Top Header Row (Simulating the header from screenshot if needed, but since sidebar remains, we add it just below Layout header) */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
        <div>
          <h1 className="text-xl text-slate-600 font-medium flex items-center gap-2">
            Dashboard <span className="text-slate-400">/</span> <span className="text-slate-900 font-semibold">CRM Overview</span>
          </h1>
        </div>
        
        <div className="flex items-center gap-4">
          <div className="relative bg-white/60 backdrop-blur-sm rounded-full px-4 py-2 flex items-center shadow-sm border border-white/40">
            <Search className="w-4 h-4 text-slate-400 mr-2" />
            <input 
              type="text" 
              placeholder="Search orders, customers, products..." 
              className="bg-transparent border-none outline-none text-sm w-64 placeholder:text-slate-400"
            />
          </div>
          
          <div className="flex items-center gap-2 bg-white/60 backdrop-blur-sm rounded-full pl-2 pr-4 py-1.5 shadow-sm border border-white/40">
            {session?.user.avatarUrl ? (
              <img src={session.user.avatarUrl} alt="" className="w-8 h-8 rounded-full" />
            ) : (
              <UserCircle className="w-8 h-8 text-slate-400" />
            )}
            <div className="flex flex-col leading-tight">
              <span className="text-sm font-semibold">{session?.user.name}</span>
              <span className="text-[10px] text-slate-500">Admin</span>
            </div>
            <ChevronDown className="w-4 h-4 text-slate-400 ml-2" />
          </div>
          
          <div className="flex items-center gap-3">
            <button className="relative p-2 bg-white/60 backdrop-blur-sm rounded-full shadow-sm border border-white/40">
              <Bell className="w-4 h-4 text-slate-600" />
              <span className="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
            </button>
            <button className="relative p-2 bg-white/60 backdrop-blur-sm rounded-full shadow-sm border border-white/40">
              <MessageSquare className="w-4 h-4 text-slate-600" />
            </button>
            <ThemeToggle />
          </div>
        </div>
      </div>

      <div className="mb-6">
        <button className="flex items-center gap-2 bg-white/60 backdrop-blur-sm border border-white/40 rounded-md px-3 py-1.5 text-sm font-medium shadow-sm">
          Last 30 Days: Jul 23, 2026 - Aug 21, 2026 <ChevronDown className="w-4 h-4" />
        </button>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4 mb-6">
        
        {/* Active Chats Card */}
        <div className="rounded-xl bg-[#1a3a29] text-white p-5 shadow-md flex flex-col justify-between overflow-hidden relative">
          <div className="z-10">
            <h3 className="text-xs font-semibold tracking-wider text-green-100/80 mb-1">ACTIVE CHATS</h3>
            <div className="flex items-baseline gap-2">
              <span className="text-3xl font-bold">{activeChats}</span>
              <span className="text-lg">Chats</span>
            </div>
            <div className="text-xs text-green-400 mt-1 flex items-center">
              ↗ +12.4% <span className="text-green-100/60 ml-1">vs last period</span>
            </div>
          </div>
          <div className="-mx-5 -mb-5 opacity-80 pt-4">
             <MiniChart data={[{v:2},{v:3},{v:2.5},{v:5},{v:4},{v:6},{v:5},{v:7}]} color="#4ade80" />
          </div>
        </div>

        {/* Total Conversations Card */}
        <div className="rounded-xl bg-white p-5 shadow-sm border border-white/50 flex flex-col justify-between overflow-hidden relative">
          <div className="z-10">
            <h3 className="text-xs font-bold tracking-wider text-slate-500 mb-1">TOTAL CONVERSATIONS</h3>
            <div className="flex items-baseline gap-2">
              <span className="text-3xl font-bold text-slate-800">{formatNumber(totalChats || 3412)}</span>
            </div>
            <div className="text-xs text-red-500 mt-1 flex items-center">
              ↘ -2.1% <span className="text-slate-400 ml-1">vs last period</span>
            </div>
          </div>
          <div className="-mx-5 -mb-5 pt-4">
             <MiniChart data={[{v:7},{v:5},{v:6},{v:4},{v:3},{v:5},{v:4},{v:6}]} color="#ef4444" />
          </div>
        </div>

        {/* Avg Response Time */}
        <div className="rounded-xl bg-white p-5 shadow-sm border border-white/50 flex flex-col justify-between overflow-hidden relative">
          <div className="z-10">
            <h3 className="text-xs font-bold tracking-wider text-slate-500 mb-1">AVG. RESPONSE TIME</h3>
            <div className="flex items-baseline gap-2">
              <span className="text-3xl font-bold text-slate-800">1.5</span>
              <span className="text-lg text-slate-600 font-semibold">min</span>
            </div>
            <div className="text-xs text-green-500 mt-1 flex items-center">
              ↗ +5.1%
            </div>
          </div>
          <div className="-mx-5 -mb-5 pt-4">
             <MiniChart data={[{v:3},{v:4},{v:3.5},{v:5},{v:4.5},{v:6},{v:5.5},{v:7}]} color="#22c55e" />
          </div>
        </div>

        {/* Customer Satisfaction */}
        <div className="rounded-xl bg-white p-5 shadow-sm border border-white/50 flex flex-col justify-between overflow-hidden relative">
          <div className="z-10">
            <h3 className="text-xs font-bold tracking-wider text-slate-500 mb-1">CUSTOMER SATISFACTION</h3>
            <div className="flex items-baseline gap-2">
              <span className="text-3xl font-bold text-slate-800">4.8/5</span>
              <span className="text-yellow-400 text-xl">★</span>
            </div>
            <div className="text-xs text-green-500 mt-1 flex items-center">
              ↗ +18.9%
            </div>
          </div>
          <div className="-mx-5 -mb-5 pt-4">
             <MiniChart data={[{v:5},{v:6},{v:5.5},{v:7},{v:6.5},{v:8},{v:7.5},{v:9}]} color="#22c55e" />
          </div>
        </div>

      </div>

      {/* Middle Row Charts */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-4 mb-6">
        
        {/* Main Chart */}
        <div className="lg:col-span-6 bg-white rounded-xl p-5 shadow-sm border border-white/50">
          <div className="flex justify-between items-center mb-6">
            <h3 className="font-bold text-sm tracking-wide text-slate-800 uppercase">Chat & Engagement Trends</h3>
            <div className="flex gap-2">
              <button className="text-xs border rounded px-2 py-1 flex items-center gap-1 text-slate-600">
                Jul 23 <ChevronDown className="w-3 h-3" />
              </button>
              <button className="text-xs border rounded px-2 py-1 flex items-center gap-1 text-slate-600">
                Order Count <ChevronDown className="w-3 h-3" />
              </button>
            </div>
          </div>
          <div className="flex justify-center items-center gap-4 text-xs font-medium text-slate-600 mb-2">
            <div className="flex items-center gap-1"><div className="w-3 h-0.5 bg-[#1a3a29]"></div> Total Chats</div>
            <div className="flex items-center gap-1"><div className="w-3 h-3 bg-[#8ba793] rounded-sm"></div> Agent Performance</div>
          </div>
          <TrendChart />
        </div>

        {/* Most Used Templates */}
        <div className="lg:col-span-3 bg-white rounded-xl p-5 shadow-sm border border-white/50 flex flex-col">
          <h3 className="font-bold text-sm tracking-wide text-slate-800 uppercase mb-4">Most Used Templates</h3>
          <div className="flex-1 flex flex-col">
            <div className="flex items-center justify-center h-44">
              <div className="w-full h-full flex items-center justify-center">
                <DonutChart />
              </div>
            </div>
            <div className="mt-4 text-[11px] text-slate-600 flex-1 flex flex-col justify-end">
              <div className="flex justify-between items-center py-2 border-b border-slate-50">
                <div className="flex items-center gap-1.5 truncate pr-2"><div className="w-1.5 h-1.5 rounded-full bg-[#1b4332] shrink-0"></div> <span className="truncate">Welcome Message</span></div>
                <span className="font-semibold text-right shrink-0">1,240 sold</span>
              </div>
              <div className="flex justify-between items-center py-2 border-b border-slate-50">
                <div className="flex items-center gap-1.5 truncate pr-2"><div className="w-1.5 h-1.5 rounded-full bg-[#40916c] shrink-0"></div> <span className="truncate">Support Follow-up</span></div>
                <span className="font-semibold text-right shrink-0">840 sold</span>
              </div>
              <div className="flex justify-between items-center py-2 border-b border-slate-50">
                <div className="flex items-center gap-1.5 truncate pr-2"><div className="w-1.5 h-1.5 rounded-full bg-[#b7b7a4] shrink-0"></div> <span className="truncate">Client Follow-up</span></div>
                <span className="font-semibold text-right shrink-0">450 sold</span>
              </div>
              <div className="flex justify-between items-center py-2">
                <div className="flex items-center gap-1.5 truncate pr-2"><div className="w-1.5 h-1.5 rounded-full bg-[#e9edc9] shrink-0"></div> <span className="truncate">White Tea</span></div>
                <span className="font-semibold text-right shrink-0">210 sold</span>
              </div>
            </div>
          </div>
        </div>

        {/* User Segments */}
        <div className="lg:col-span-3 bg-white rounded-xl p-5 shadow-sm border border-white/50 flex flex-col">
          <h3 className="font-bold text-sm tracking-wide text-slate-800 uppercase mb-4">User Segments</h3>
          <SegmentsChart />
          <div className="mt-auto space-y-2 text-sm text-slate-600 font-medium">
             <div className="flex justify-between">
                <span>New Lead</span>
                <span>32%</span>
             </div>
             <div className="flex justify-between">
                <span>Active Client</span>
                <span>38%</span>
             </div>
             <div className="flex justify-between">
                <span>Inquiry</span>
                <span>0%</span>
             </div>
          </div>
        </div>

      </div>

      {/* Bottom Row */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
        
        {/* Recent Chats Table */}
        <div className="lg:col-span-6 bg-white rounded-xl p-5 shadow-sm border border-white/50 overflow-auto">
          <h3 className="font-bold text-sm tracking-wide text-slate-800 uppercase mb-4">Recent Chats</h3>
          <table className="w-full text-left text-sm">
            <thead>
              <tr className="text-slate-500 font-semibold border-b border-slate-100">
                <th className="pb-3 font-medium">Chat ID</th>
                <th className="pb-3 font-medium">User Name</th>
                <th className="pb-3 font-medium">Last Message Date</th>
                <th className="pb-3 font-medium">Chat Status</th>
                <th className="pb-3 font-medium">Last Agent</th>
                <th className="pb-3 font-medium text-right">Action</th>
              </tr>
            </thead>
            <tbody className="text-slate-700">
              {recentChats.map((chat) => (
                <tr key={chat.id} className="border-b border-slate-50 last:border-0">
                  <td className="py-3">00310{chat.id.substring(0,3)}</td>
                  <td className="py-3 font-medium text-slate-800">{chat.contact?.name || "Unknown"}</td>
                  <td className="py-3">{format(new Date(chat.lastMessageAt), 'MMM dd, yyyy')}</td>
                  <td className="py-3">
                    <span className={`px-2 py-1 rounded-md text-xs font-semibold ${
                      chat.status === "OPEN" ? "bg-green-100 text-green-700" :
                      chat.status === "PENDING" ? "bg-yellow-100 text-yellow-700" :
                      "bg-red-100 text-red-700"
                    }`}>
                      {chat.status === "OPEN" ? "Active" : chat.status === "PENDING" ? "Queued" : "Closed"}
                    </span>
                  </td>
                  <td className="py-3">{chat.assignee?.name || "Open Chat"}</td>
                  <td className="py-3">
                    <div className="flex items-center justify-end gap-2 text-slate-400">
                      <button><Eye className="w-4 h-4 hover:text-slate-600" /></button>
                      <button><Pencil className="w-4 h-4 hover:text-slate-600" /></button>
                    </div>
                  </td>
                </tr>
              ))}
              {recentChats.length === 0 && (
                <tr className="border-b border-slate-50 last:border-0">
                  <td className="py-3">00310001</td>
                  <td className="py-3 font-medium text-slate-800">Arjun Singh</td>
                  <td className="py-3">Jul 23, 2026</td>
                  <td className="py-3">
                    <span className="px-2 py-1 rounded-md text-xs font-semibold bg-green-100 text-green-700">Active</span>
                  </td>
                  <td className="py-3">Open Chat</td>
                  <td className="py-3">
                    <div className="flex items-center justify-end gap-2 text-slate-400">
                      <button><Eye className="w-4 h-4 hover:text-slate-600" /></button>
                      <button><Pencil className="w-4 h-4 hover:text-slate-600" /></button>
                    </div>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Template Approvals */}
        <div className="lg:col-span-3 bg-white rounded-xl p-5 shadow-sm border border-white/50">
          <h3 className="font-bold text-sm tracking-wide text-slate-800 uppercase mb-4">Template Approvals</h3>
          <div className="space-y-4">
            {templates.map((tpl) => (
              <div key={tpl.id} className="flex justify-between items-center pb-3 border-b border-slate-50 last:border-0">
                <span className="text-sm font-medium text-slate-700">{tpl.name}</span>
                <span className="px-2 py-1 bg-green-100 text-green-700 text-xs rounded font-semibold">{tpl.metaStatus === "APPROVED" ? "Status" : tpl.metaStatus}</span>
              </div>
            ))}
            {templates.length === 0 && (
               <>
                <div className="flex justify-between items-center pb-3 border-b border-slate-50">
                  <span className="text-sm font-medium text-slate-700">Custom Template</span>
                  <span className="px-2 py-1 bg-green-100 text-green-700 text-xs rounded font-semibold">Status</span>
                </div>
                <div className="flex justify-between items-center pb-3 border-b border-slate-50">
                  <span className="text-sm font-medium text-slate-700">Custom Template 2</span>
                  <span className="px-2 py-1 bg-green-100 text-green-700 text-xs rounded font-semibold">Status</span>
                </div>
               </>
            )}
            <div className="text-center text-sm text-slate-400 mt-8">
              No templates pending
            </div>
          </div>
        </div>

        {/* Agent Efficiency */}
        <div className="lg:col-span-3 bg-white rounded-xl p-5 shadow-sm border border-white/50">
          <div className="flex justify-between items-center mb-4">
            <h3 className="font-bold text-sm tracking-wide text-slate-800 uppercase">Agent Efficiency</h3>
          </div>
          <div className="flex justify-between text-xs font-semibold text-slate-500 mb-3">
             <span>Top Agent</span>
             <span>Response time</span>
          </div>
          <div className="space-y-4">
            {agents.map((agent) => (
              <div key={agent.id} className="flex justify-between items-center">
                <div className="flex items-center gap-3">
                  {agent.avatarUrl ? (
                    <img src={agent.avatarUrl} alt="" className="w-8 h-8 rounded-full" />
                  ) : (
                    <div className="w-8 h-8 rounded-full bg-slate-200 flex items-center justify-center">
                      <UserCircle className="w-6 h-6 text-slate-400" />
                    </div>
                  )}
                  <span className="text-sm font-medium text-slate-800">{agent.name}</span>
                </div>
                <span className="text-sm text-slate-400 font-medium">1.5 <span className="text-xs">min</span></span>
              </div>
            ))}
            {agents.length === 0 && (
              <div className="flex justify-between items-center">
                <div className="flex items-center gap-3">
                   <div className="w-8 h-8 rounded-full bg-slate-200 flex items-center justify-center">
                      <UserCircle className="w-6 h-6 text-slate-400" />
                   </div>
                  <span className="text-sm font-medium text-slate-800">Arjun Singh</span>
                </div>
                <span className="text-sm text-slate-400 font-medium">1.5 <span className="text-xs">min</span></span>
              </div>
            )}
          </div>
        </div>

      </div>
    </div>
  );
}
