"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { ArrowLeft, Save, Plus, X, Loader2, Trash2, CheckCircle2 } from "lucide-react";
import { Button } from "@/presentation/components/ui/button";
import { Input } from "@/presentation/components/ui/input";
import { Switch } from "@/presentation/components/ui/switch";
import { Label } from "@/presentation/components/ui/label";
import { RichTextEditor } from "@/presentation/components/ui/rich-text-editor";
import { PaginatedCategorySelect } from "@/app/(dashboard)/help-center/components/paginated-category-select";
import { PaginatedSectionSelect } from "@/app/(dashboard)/help-center/components/paginated-section-select";
import { ROUTES } from "@/shared/constants";
import { useT } from "@/shared/i18n/client";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useHelpArticleBlocks } from "@/presentation/hooks/use-help-article-blocks";
import { useRepositories } from "@/di/repository-provider";
import { toast } from "sonner";

export default function EditArticlePage() {
  const router = useRouter();
  const params = useParams();
  const id = params.id as string;
  const t = useT();
  const { helpArticleRepository } = useRepositories();
  usePageHeader("", "");
  const [isDraft, setIsDraft] = useState(true);
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [section, setSection] = useState("");
  const [category, setCategory] = useState("");
  const [tagInput, setTagInput] = useState("");
  const [tags, setTags] = useState<string[]>([]);
  const [isSaving, setIsSaving] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [selectedCategoryLabel, setSelectedCategoryLabel] = useState<string | undefined>(undefined);
  const [selectedSectionLabel, setSelectedSectionLabel] = useState<string | undefined>(undefined);
  // Blocks are tinted with the tone of the chosen category, so they follow the select above.
  const { blocks, templates } = useHelpArticleBlocks(category);

  const { data: articleData, loading: loadingArticle, error: articleError } = useApiQuery(
    () => helpArticleRepository.findById(id),
    { deps: [id] }
  );

  useEffect(() => {
    if (!loadingArticle) {
      if (articleError || !articleData) {
        toast.error("Article introuvable");
        router.push(ROUTES.helpCenter || "/");
      } else {
        setTitle(articleData.title || "");
        setContent(articleData.content || "");
        
        // Handle different formats the API might return for section
        const sectionRaw = articleData.section as unknown;
        const sectionValue = articleData.help_section_id?.toString() ||
                            (typeof sectionRaw === "object" && sectionRaw !== null && "id" in sectionRaw
                              ? String((sectionRaw as { id?: string | number }).id ?? "")
                              : typeof sectionRaw === "string"
                                ? sectionRaw
                                : "");
        setSection(sectionValue);
        const sectionName =
          typeof sectionRaw === "object" && sectionRaw !== null && "name" in sectionRaw
            ? (sectionRaw as { name?: string }).name
            : undefined;
        setSelectedSectionLabel(sectionName);

        // Handle different formats the API might return for category
        const categoryValue = articleData.help_category_id?.toString() ||
                             articleData.category_id?.toString() ||
                             articleData.category?.id?.toString() ||
                             articleData.category?.toString() ||
                             "";
        setCategory(categoryValue);
        setSelectedCategoryLabel(articleData.category?.name);
        setIsDraft(articleData.is_draft ?? true);
        setTags(articleData.tags || []);
      }
    }
  }, [articleData, loadingArticle, articleError, router]);

  const handleAddTag = () => {
    if (!tagInput.trim()) return;
    if (tagInput.trim().length > 30) {
      toast.error("Un tag ne peut pas dépasser 30 caractères");
      return;
    }
    if (!tags.includes(tagInput.trim())) {
      setTags([...tags, tagInput.trim()]);
      setTagInput("");
    }
  };

  const handleRemoveTag = (tagToRemove: string) => {
    setTags(tags.filter((tag) => tag !== tagToRemove));
  };

  const handleSave = async () => {
    if (!title.trim()) {
      toast.error("Le titre est requis");
      return;
    }
    if (!section) {
      toast.error("La section est requise");
      return;
    }
    if (!category) {
      toast.error("La catégorie est requise");
      return;
    }

    setIsSaving(true);
    try {
      await helpArticleRepository.update(id, {
        title,
        content,
        help_section_id: section,
        help_category_id: category,
        is_draft: isDraft,
        tags
      });

      toast.success("Article mis à jour avec succès");
      router.push(ROUTES.helpCenter || "/");
    } catch (error: any) {
      toast.error(error.response?.data?.message || "Une erreur est survenue lors de la mise à jour");
      setIsSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!confirm("Êtes-vous sûr de vouloir supprimer cet article ?")) return;
    
    setIsDeleting(true);
    try {
      await helpArticleRepository.delete(id);
      toast.success("Article supprimé avec succès");
      router.push(ROUTES.helpCenter || "/");
    } catch (error: any) {
      toast.error(error.response?.data?.message || "Erreur lors de la suppression");
      setIsDeleting(false);
    }
  };

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

  return (
    <div className="flex flex-col min-h-full">
      {/* Page Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between p-6 bg-background border-b border-border gap-4">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" asChild className="text-muted-foreground hover:text-foreground">
            <Link href={ROUTES.helpCenter || "/"}>
              <ArrowLeft className="w-5 h-5" />
            </Link>
          </Button>
          <div>
            <h1 className="text-2xl font-bold text-foreground">
              Modifier l'article
            </h1>
            <p className="text-sm text-muted-foreground">
              {t.pages?.helpCenterCreate?.subtitle || "Centre d'Aide"}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-6">
          <div className="flex items-center gap-2">
            <Switch
              id="publish-mode"
              checked={!isDraft}
              onCheckedChange={(checked) => setIsDraft(!checked)}
            />
            <Label 
              htmlFor="publish-mode" 
              className={`text-sm font-medium cursor-pointer flex items-center gap-1.5 ${!isDraft ? 'text-emerald-600' : 'text-muted-foreground'}`}
            >
              {!isDraft && <CheckCircle2 className="w-4 h-4" />}
              {!isDraft ? "Publié" : "Brouillon"}
            </Label>
          </div>
          <Button 
            variant="destructive" 
            onClick={handleDelete} 
            disabled={isDeleting}
            className="gap-2"
          >
            {isDeleting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
            Supprimer
          </Button>
          <Button onClick={handleSave} disabled={isSaving} className="bg-blue-600 hover:bg-blue-700 text-white gap-2">
            {isSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
            Enregistrer
          </Button>
        </div>
      </div>

      {/* Main Content */}
      <div className="flex-1 p-6 bg-muted/30">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 max-w-7xl mx-auto">
          {/* Left Column */}
          <div className="lg:col-span-2 space-y-6">
            {/* Title Card */}
            <div className="bg-card rounded-xl border border-border shadow-sm p-6">
              <Label htmlFor="title" className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 block">
                Titre de l'article *
              </Label>
              <Input
                id="title"
                placeholder="Ex: Comment accéder à votre tableau de bord"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                className="w-full"
              />
            </div>

            {/* Content Card */}
            <div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden flex flex-col h-[600px]">
              <RichTextEditor
                value={content}
                onChange={setContent}
                blocks={blocks}
                templates={templates}
                placeholder="Rédigez votre article ici..."
                className="border-0 rounded-none h-full bg-card"
              />
            </div>
          </div>

          {/* Right Column */}
          <div className="space-y-6">
            {/* Classification Card */}
            <div className="bg-card rounded-xl border border-border shadow-sm p-6 space-y-5">
              <div className="flex items-center gap-2 mb-2 text-blue-600">
                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>
                <h3 className="font-semibold text-foreground">Classification</h3>
              </div>

              <div className="space-y-2">
                <Label htmlFor="section" className="text-sm font-medium">
                  Section *
                </Label>
                <PaginatedSectionSelect
                  value={section || undefined}
                  onValueChange={(v) => { setSection(v); setSelectedSectionLabel(undefined); }}
                  selectedLabel={selectedSectionLabel}
                  placeholder={loadingArticle ? "Chargement..." : "Choisir une section"}
                  disabled={loadingArticle}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="category" className="text-sm font-medium">
                  Catégorie *
                </Label>
                <PaginatedCategorySelect
                  value={category || undefined}
                  onValueChange={(v) => { setCategory(v); setSelectedCategoryLabel(undefined); }}
                  selectedLabel={selectedCategoryLabel}
                  placeholder={loadingArticle ? "Chargement..." : "Choisir une catégorie"}
                  disabled={loadingArticle}
                />
              </div>
            </div>

            {/* Tags Card */}
            <div className="bg-card rounded-xl border border-border shadow-sm p-6 space-y-5">
              <div className="flex items-center gap-2 mb-2 text-blue-600">
                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"/><circle cx="7.5" cy="7.5" r=".5" fill="currentColor"/></svg>
                <h3 className="font-semibold text-foreground">Tags</h3>
              </div>

              <div className="flex gap-2">
                <Input
                  placeholder="Ajouter un tag..."
                  value={tagInput}
                  onChange={(e) => setTagInput(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter') {
                      e.preventDefault();
                      handleAddTag();
                    }
                  }}
                  className="flex-1"
                />
                <Button variant="outline" size="icon" onClick={handleAddTag} type="button">
                  <Plus className="w-4 h-4" />
                </Button>
              </div>

              <div className="flex flex-wrap gap-2 min-h-[40px]">
                {tags.length > 0 ? (
                  tags.map((tag) => (
                    <span
                      key={tag}
                      className="inline-flex items-center gap-1 px-2.5 py-1 rounded-md bg-secondary text-secondary-foreground text-xs font-medium"
                    >
                      {tag}
                      <button
                        onClick={() => handleRemoveTag(tag)}
                        className="text-secondary-foreground/70 hover:text-secondary-foreground"
                      >
                        <X className="w-3 h-3" />
                      </button>
                    </span>
                  ))
                ) : (
                  <p className="text-sm text-muted-foreground italic">Aucun tag ajouté</p>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
