"use client";

// ============================================================================
// Dashboard Home Page
// ============================================================================

import React, { useEffect, useState } from "react";
import { DashboardHeader } from "@/components/layout/dashboard-header";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { analyticsApi } from "@/lib/api";
import {
  formatCurrency,
  formatNumber,
  formatMetric,
  formatPercent,
} from "@/lib/utils/format";
import {
  BarChart3,
  TrendingUp,
  Users,
  ShoppingCart,
  Loader2,
} from "lucide-react";
import type { SpendingAnalytics } from "@/lib/types/api";
import { useTargetChannel } from "@/components/providers/target-channel-provider";

export default function DashboardPage() {
  const { selectedChannel } = useTargetChannel();
  const [spending, setSpending] = useState<SpendingAnalytics | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!selectedChannel) {
      setLoading(false);
      return;
    }

    const loadData = async () => {
      try {
        setLoading(true);
        const data = await analyticsApi.spending({
          grouping: "week",
          target_channel_id: selectedChannel.id,
        });
        setSpending(data);
      } catch (error) {
        console.error("Error loading spending data:", error);
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, [selectedChannel]);

  if (!selectedChannel) {
    return (
      <>
        <DashboardHeader breadcrumbs={[{ label: "Главная" }]} />
        <div className="flex flex-1 items-center justify-center">
          <div className="text-center">
            <h2 className="text-2xl font-semibold mb-2">
              Выберите целевой канал
            </h2>
            <p className="text-muted-foreground">
              Для начала работы выберите целевой канал в верхнем меню
            </p>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <DashboardHeader breadcrumbs={[{ label: "Главная" }]} />
      <div className="flex flex-1 flex-col gap-4 p-4 pt-0 mt-4">
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">
                Всего закупов
              </CardTitle>
              <ShoppingCart className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              {loading ? (
                <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              ) : (
                <>
                  <div className="text-2xl font-bold">
                    {formatNumber(spending?.total_cost)}
                  </div>
                  <p className="text-xs text-muted-foreground">
                    {formatNumber(0 || 0, true)} за прошлый месяц
                  </p>
                </>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">
                Подписчиков привлечено
              </CardTitle>
              <Users className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              {loading ? (
                <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              ) : (
                <>
                  <div className="text-2xl font-bold">
                    {formatNumber(spending?.total_subscriptions)}
                  </div>
                  <p className="text-xs text-muted-foreground">
                    {formatNumber(0 || 0, true)} за прошлый месяц
                  </p>
                </>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Средний CPF</CardTitle>
              <TrendingUp className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              {loading ? (
                <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              ) : (
                <>
                  <div className="text-2xl font-bold">
                    ₽{formatMetric(spending?.avg_cpf)}
                  </div>
                  <p className="text-xs text-muted-foreground">
                    {formatPercent(0 || 0, true)} от прошлого месяца
                  </p>
                </>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Средний CPM</CardTitle>
              <BarChart3 className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              {loading ? (
                <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              ) : (
                <>
                  <div className="text-2xl font-bold">
                    ₽{formatMetric(spending?.avg_cpm)}
                  </div>
                  <p className="text-xs text-muted-foreground">
                    {formatPercent(0 || 0, true)} от прошлого месяца
                  </p>
                </>
              )}
            </CardContent>
          </Card>
        </div>

        <div className="grid gap-4 md:grid-cols-1">
          <Card>
            <CardHeader>
              <CardTitle>Быстрый старт</CardTitle>
              <CardDescription>Начните с основных действий</CardDescription>
            </CardHeader>
            <CardContent className="space-y-2">
              <a
                href="/purchases/new"
                className="block text-sm text-primary hover:underline"
              >
                → Создать новый закуп
              </a>
              <a
                href="/creatives/new"
                className="block text-sm text-primary hover:underline"
              >
                → Создать креатив
              </a>
              <a
                href="/external-channels/import"
                className="block text-sm text-primary hover:underline"
              >
                → Импортировать каналы
              </a>
              <a
                href="/analytics"
                className="block text-sm text-primary hover:underline"
              >
                → Посмотреть аналитику
              </a>
            </CardContent>
          </Card>
        </div>
      </div>
    </>
  );
}
