'use client';

import { useQuery } from '@tanstack/react-query';
import Link from 'next/link';
import { useAuthStore } from '@/store/auth';
import { dashboardApi } from '@/lib/api';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Users,
  Building2,
  ClipboardList,
  Wrench,
  FileText,
  Bell,
  CreditCard,
  TrendingUp,
  AlertTriangle,
  CheckCircle,
  Clock,
  PlayCircle,
  XCircle,
  Archive,
  PauseCircle,
} from 'lucide-react';

export default function DashboardPage() {
  const { user } = useAuthStore();

  const { data: stats, isLoading } = useQuery({
    queryKey: ['dashboard-stats'],
    queryFn: () => dashboardApi.getStats(),
  });

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold">Dashboard</h1>
        <p className="text-muted-foreground">
          Welcome back, {user?.first_name || 'Admin'}
        </p>
      </div>

      {/* Main Stats */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Link href="/users">
          <Card className="hover:bg-muted/50 transition-colors cursor-pointer">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total Users</CardTitle>
              <Users className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {isLoading ? '-' : stats?.users.total.toLocaleString()}
              </div>
              <p className="text-xs text-muted-foreground">
                {isLoading ? '' : `${stats?.users.active} active, ${stats?.users.new_30d} new this month`}
              </p>
            </CardContent>
          </Card>
        </Link>

        <Link href="/residences">
          <Card className="hover:bg-muted/50 transition-colors cursor-pointer">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Residences</CardTitle>
              <Building2 className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {isLoading ? '-' : stats?.residences.total.toLocaleString()}
              </div>
              <p className="text-xs text-muted-foreground">
                {isLoading ? '' : `${stats?.residences.active} active, ${stats?.residences.new_30d} new this month`}
              </p>
            </CardContent>
          </Card>
        </Link>

        <Link href="/tasks">
          <Card className="hover:bg-muted/50 transition-colors cursor-pointer">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Tasks</CardTitle>
              <ClipboardList className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {isLoading ? '-' : stats?.tasks.total.toLocaleString()}
              </div>
              <p className="text-xs text-muted-foreground">
                {isLoading ? '' : `${stats?.tasks.active} active, ${stats?.tasks.new_30d} new this month`}
              </p>
            </CardContent>
          </Card>
        </Link>

        <Link href="/contractors">
          <Card className="hover:bg-muted/50 transition-colors cursor-pointer">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Contractors</CardTitle>
              <Wrench className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {isLoading ? '-' : stats?.contractors.total.toLocaleString()}
              </div>
              <p className="text-xs text-muted-foreground">
                {isLoading ? '' : `${stats?.contractors.active} active, ${stats?.contractors.favorite} favorites`}
              </p>
            </CardContent>
          </Card>
        </Link>
      </div>

      {/* Secondary Stats */}
      <div className="grid gap-4 md:grid-cols-3">
        <Link href="/documents">
          <Card className="hover:bg-muted/50 transition-colors cursor-pointer">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Documents</CardTitle>
              <FileText className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {isLoading ? '-' : stats?.documents.total.toLocaleString()}
              </div>
              <p className="text-xs text-muted-foreground">
                {isLoading ? '' : `${stats?.documents.active} active`}
                {!isLoading && stats?.documents.expired ? (
                  <span className="text-red-500 ml-1">({stats.documents.expired} expired)</span>
                ) : null}
              </p>
            </CardContent>
          </Card>
        </Link>

        <Link href="/notifications">
          <Card className="hover:bg-muted/50 transition-colors cursor-pointer">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Notifications</CardTitle>
              <Bell className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {isLoading ? '-' : stats?.notifications.total.toLocaleString()}
              </div>
              <p className="text-xs text-muted-foreground">
                {isLoading ? '' : `${stats?.notifications.sent} sent, ${stats?.notifications.pending} pending`}
              </p>
            </CardContent>
          </Card>
        </Link>

        <Link href="/subscriptions">
          <Card className="hover:bg-muted/50 transition-colors cursor-pointer">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Subscriptions</CardTitle>
              <CreditCard className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {isLoading ? '-' : stats?.subscriptions.total.toLocaleString()}
              </div>
              <p className="text-xs text-muted-foreground">
                {isLoading ? '' : `${(stats?.subscriptions.premium || 0) + (stats?.subscriptions.pro || 0)} paid`}
              </p>
            </CardContent>
          </Card>
        </Link>
      </div>

      {/* Task Status Overview */}
      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <ClipboardList className="h-5 w-5" />
              Task Status Overview
            </CardTitle>
            <CardDescription>
              {isLoading ? 'Loading...' : `${stats?.tasks.total} total tasks across all residences`}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 gap-3">
              {/* Overdue - Highlighted at top */}
              {!isLoading && (stats?.tasks.overdue ?? 0) > 0 && (
                <div className="flex items-center gap-3 p-3 bg-red-50 rounded-lg col-span-2 border border-red-200">
                  <AlertTriangle className="h-8 w-8 text-red-600" />
                  <div>
                    <div className="text-2xl font-bold text-red-700">
                      {stats?.tasks.overdue}
                    </div>
                    <div className="text-sm text-red-600">Overdue</div>
                  </div>
                </div>
              )}

              {/* Active statuses */}
              <div className="flex items-center gap-3 p-3 bg-yellow-50 rounded-lg">
                <Clock className="h-6 w-6 text-yellow-600" />
                <div>
                  <div className="text-xl font-bold text-yellow-700">
                    {isLoading ? '-' : stats?.tasks.pending}
                  </div>
                  <div className="text-sm text-yellow-600">Pending</div>
                </div>
              </div>

              <div className="flex items-center gap-3 p-3 bg-blue-50 rounded-lg">
                <PlayCircle className="h-6 w-6 text-blue-600" />
                <div>
                  <div className="text-xl font-bold text-blue-700">
                    {isLoading ? '-' : stats?.tasks.in_progress}
                  </div>
                  <div className="text-sm text-blue-600">In Progress</div>
                </div>
              </div>

              <div className="flex items-center gap-3 p-3 bg-orange-50 rounded-lg">
                <PauseCircle className="h-6 w-6 text-orange-600" />
                <div>
                  <div className="text-xl font-bold text-orange-700">
                    {isLoading ? '-' : stats?.tasks.on_hold}
                  </div>
                  <div className="text-sm text-orange-600">On Hold</div>
                </div>
              </div>

              <div className="flex items-center gap-3 p-3 bg-green-50 rounded-lg">
                <CheckCircle className="h-6 w-6 text-green-600" />
                <div>
                  <div className="text-xl font-bold text-green-700">
                    {isLoading ? '-' : stats?.tasks.completed}
                  </div>
                  <div className="text-sm text-green-600">Completed</div>
                </div>
              </div>

              {/* Archived and Cancelled - smaller at bottom */}
              <div className="flex items-center justify-between p-2 bg-gray-100 rounded-lg col-span-2">
                <div className="flex items-center gap-2">
                  <XCircle className="h-4 w-4 text-gray-400" />
                  <span className="text-sm text-gray-500">
                    {isLoading ? '-' : stats?.tasks.cancelled} cancelled
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <Archive className="h-4 w-4 text-gray-400" />
                  <span className="text-sm text-gray-500">
                    {isLoading ? '-' : stats?.tasks.archived} archived
                  </span>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <TrendingUp className="h-5 w-5" />
              Subscription Distribution
            </CardTitle>
            <CardDescription>User subscription tiers</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium">Free</span>
                <div className="flex items-center gap-2">
                  <div className="w-32 h-2 bg-gray-200 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-gray-500 rounded-full"
                      style={{
                        width: stats?.subscriptions.total
                          ? `${(stats.subscriptions.free / stats.subscriptions.total) * 100}%`
                          : '0%',
                      }}
                    />
                  </div>
                  <span className="text-sm text-muted-foreground w-12 text-right">
                    {isLoading ? '-' : stats?.subscriptions.free}
                  </span>
                </div>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium">Premium</span>
                <div className="flex items-center gap-2">
                  <div className="w-32 h-2 bg-gray-200 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-blue-500 rounded-full"
                      style={{
                        width: stats?.subscriptions.total
                          ? `${(stats.subscriptions.premium / stats.subscriptions.total) * 100}%`
                          : '0%',
                      }}
                    />
                  </div>
                  <span className="text-sm text-muted-foreground w-12 text-right">
                    {isLoading ? '-' : stats?.subscriptions.premium}
                  </span>
                </div>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium">Pro</span>
                <div className="flex items-center gap-2">
                  <div className="w-32 h-2 bg-gray-200 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-purple-500 rounded-full"
                      style={{
                        width: stats?.subscriptions.total
                          ? `${(stats.subscriptions.pro / stats.subscriptions.total) * 100}%`
                          : '0%',
                      }}
                    />
                  </div>
                  <span className="text-sm text-muted-foreground w-12 text-right">
                    {isLoading ? '-' : stats?.subscriptions.pro}
                  </span>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
