"use client";

import Link from "next/link";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useRepositories } from "@/di/repository-provider";
import { Loader2, FileText, Eye, ThumbsUp, BookOpen, Plus, Settings, BarChart2, Star } from "lucide-react";
import { useT } from "@/shared/i18n/client";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { ROUTES } from "@/shared/constants";
import { Button } from "@/presentation/components/ui/button";
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from "@/presentation/components/ui/tabs";
import StatsCard from "@/presentation/components/shared/stats-card";
import { SectionsTab } from "./components/sections-tab";
import { CategoriesTab } from "./components/categories-tab";
import { ArticlesTab } from "./components/articles-tab";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  Legend
} from "recharts";

const COLORS = ['#2563eb', '#16a34a', '#ea580c']; // blue, green, orange

export default function HelpCenterPage() {
  const t = useT();
  const { helpArticleRepository } = useRepositories();
  // Clear the header to match the design where title is in the page content
  usePageHeader("", "");

  const { data: statsData, loading } = useApiQuery(
    () => helpArticleRepository.getStats(),
    { deps: [] }
  );

  const { data: categoryOptions } = useApiQuery(
    () => helpArticleRepository.getCategoryOptions(),
    { deps: [] }
  );

  const getCategoryName = (categoryId: unknown): string => {
    if (categoryId === undefined || categoryId === null || categoryId === "") return "";
    const idStr = String(categoryId);
    if (!categoryOptions || !Array.isArray(categoryOptions)) return idStr;
    const match = categoryOptions.find((item: any) => {
      if (typeof item === 'string') return item === idStr;
      const id = item.id?.toString() || item.value?.toString() || item.name;
      return id === idStr;
    });
    if (!match) return idStr;
    if (typeof match === 'string') return match;
    return match.label || match.label_fr || match.name || match.title || idStr;
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full min-h-[400px]">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  // Use API data or fallback to empty arrays if API fails/returns empty
  const feedbackEvolution = statsData?.feedback_evolution || [];
  const audienceDistribution = statsData?.audience_distribution || [];
  const categorySatisfactionData = statsData?.satisfaction_by_category || [];

  return (
    <div className="flex flex-col min-h-full">
      {/* Custom Page Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between p-6 bg-background gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground">
            {t.pages?.helpCenter?.title || "Centre d'Aide"}
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            {t.pages?.helpCenter?.subtitle || "Gérez les articles, sections et analysez les retours utilisateurs"}
          </p>
        </div>
        <div className="flex items-center gap-3">
          <Button asChild className="bg-blue-600 hover:bg-blue-700 text-white gap-2">
            <Link href={ROUTES.helpCenterCreate || "/help-center/create"}>
              <Plus className="w-4 h-4" />
              Nouvel article
            </Link>
          </Button>
        </div>
      </div>

      <div className="p-6 pt-0 space-y-6">
        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <StatsCard 
            title="ARTICLES PUBLIÉS" 
            value={statsData?.total_published ?? "0"} 
            subtitle={`${statsData?.total_articles ?? "0"} au total`} 
            icon={FileText} 
            accent="blue" 
          />
          <StatsCard 
            title="VUES TOTALES" 
            value={statsData?.total_views ?? "0"} 
            subtitle="Tous articles confondus" 
            icon={Eye} 
            accent="purple" 
          />
          <StatsCard 
            title="TAUX DE SATISFACTION" 
            value={`${statsData?.satisfaction_rate ?? "0"}%`} 
            subtitle="évaluations" 
            icon={ThumbsUp} 
            accent="green" 
          />
          <StatsCard 
            title="SECTIONS ACTIVES" 
            value={statsData?.active_sections_count ?? "0"} 
            subtitle="Conducteurs & Gestionnaires" 
            icon={BookOpen} 
            accent="purple" 
          />
        </div>

        {/* Main Content Tabs */}
        <Tabs defaultValue="overview" className="w-full">
          <TabsList className="bg-transparent h-auto p-0 gap-6 border-b border-border w-full justify-start rounded-none">
            <TabsTrigger 
              value="overview" 
              className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-blue-600 rounded-none px-2 py-3 gap-2"
            >
              <BarChart2 className="w-4 h-4" />
              Vue d'ensemble
            </TabsTrigger>
            <TabsTrigger 
              value="articles" 
              className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-blue-600 rounded-none px-2 py-3 gap-2"
            >
              <FileText className="w-4 h-4" />
              Articles
            </TabsTrigger>
            <TabsTrigger 
              value="feedback" 
              className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-blue-600 rounded-none px-2 py-3 gap-2"
            >
              <Star className="w-4 h-4" />
              Feedback
            </TabsTrigger>
            <TabsTrigger 
              value="sections" 
              className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-blue-600 rounded-none px-2 py-3 gap-2"
            >
              <BookOpen className="w-4 h-4" />
              Sections
            </TabsTrigger>
            <TabsTrigger 
              value="categories" 
              className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-blue-600 rounded-none px-2 py-3 gap-2"
            >
              <Settings className="w-4 h-4" />
              Catégories
            </TabsTrigger>
          </TabsList>
          
          <TabsContent value="overview" className="space-y-6 pt-6">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* Feedback Chart */}
              <div className="bg-card rounded-xl border border-border shadow-sm p-6">
                <div className="flex items-center gap-2 mb-6">
                  <BarChart2 className="w-5 h-5 text-blue-600" />
                  <h3 className="font-semibold text-foreground">Évolution du feedback (6 mois)</h3>
                </div>
                <div className="h-[300px] w-full">
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={feedbackEvolution} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                      <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
                      <XAxis dataKey="month" axisLine={false} tickLine={false} tick={{ fontSize: 12, fill: 'hsl(var(--muted-foreground))' }} />
                      <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 12, fill: 'hsl(var(--muted-foreground))' }} />
                      <Tooltip 
                        cursor={{ fill: 'hsl(var(--muted))' }}
                        contentStyle={{ borderRadius: '8px', border: '1px solid hsl(var(--border))', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)' }}
                      />
                      <Bar dataKey="satisfaction" fill="#16a34a" radius={[4, 4, 0, 0]} barSize={30} />
                      <Bar dataKey="dissatisfaction" fill="#dc2626" radius={[4, 4, 0, 0]} barSize={30} />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </div>

              {/* Audience Chart */}
              <div className="bg-card rounded-xl border border-border shadow-sm p-6">
                <div className="flex items-center gap-2 mb-6">
                  <svg className="w-5 h-5 text-blue-600" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
                  <h3 className="font-semibold text-foreground">Répartition par audience</h3>
                </div>
                <div className="h-[300px] w-full flex flex-col">
                  <div className="flex-1 min-h-0">
                    <ResponsiveContainer width="100%" height="100%">
                      <PieChart>
                        <Pie
                          data={audienceDistribution}
                          cx="50%"
                          cy="50%"
                          innerRadius={70}
                          outerRadius={100}
                          paddingAngle={2}
                          dataKey="count"
                          nameKey="section"
                          stroke="none"
                        >
                          {audienceDistribution.map((_: any, index: number) => (
                            <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                          ))}
                        </Pie>
                        <Tooltip 
                          contentStyle={{ borderRadius: '8px', border: '1px solid hsl(var(--border))', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)' }}
                        />
                        <Legend 
                          verticalAlign="bottom" 
                          height={36}
                          iconType="circle"
                          formatter={(value) => <span className="text-sm text-foreground ml-1">{value}</span>}
                        />
                      </PieChart>
                    </ResponsiveContainer>
                  </div>
                </div>
              </div>
            </div>

            {/* Satisfaction by Category */}
            <div className="bg-card rounded-xl border border-border shadow-sm p-6">
              <h3 className="font-semibold text-foreground mb-6">Satisfaction par catégorie</h3>
              <div className="space-y-5">
                {categorySatisfactionData.map((item: any, index: number) => {
                  const rawCategory = item.category?.label || item.category?.label_fr || item.category?.name || item.name || item.category_id;
                  const categoryName = getCategoryName(rawCategory);

                  return (
                    <div key={item.category_id || item.name || index} className="flex items-center gap-4">
                      <div className="w-1/3 min-w-[200px] text-sm text-foreground font-medium truncate" title={categoryName}>
                        {categoryName}
                      </div>
                      <div className="flex-1 h-3 bg-muted rounded-full overflow-hidden">
                        <div 
                          className="h-full bg-emerald-500 rounded-full" 
                          style={{ width: `${item.value || (item.average_score * 20)}%` }}
                        />
                      </div>
                      <div className="w-12 text-right text-sm font-bold text-foreground">
                        {item.value || (item.average_score * 20)}%
                      </div>
                      <div className="w-20 text-right text-xs text-muted-foreground">
                        {item.views || item.total_views} vues
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </TabsContent>
          
          <TabsContent value="articles" className="pt-6">
            <ArticlesTab />
          </TabsContent>
          
          <TabsContent value="feedback" className="pt-6">
            <div className="bg-card rounded-xl border border-border shadow-sm p-6 text-center text-muted-foreground">
              Contenu de l'onglet Feedback
            </div>
          </TabsContent>
          
          <TabsContent value="sections" className="pt-6">
            <SectionsTab />
          </TabsContent>

          <TabsContent value="categories" className="pt-6">
            <CategoriesTab />
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}
