"use client";

import { useState } from "react";
import {
  ArrowLeft,
  Copy,
  Check,
  Save,
  Trash2,
  History,
  Sparkles,
  Search,
  Image,
} from "lucide-react";
import { Button } from "@/shared/components/ui/button";
import { Input } from "@/shared/components/ui/input";
import { Label } from "@/shared/components/ui/label";
import { Textarea } from "@/shared/components/ui/textarea";
import { Badge } from "@/shared/components/ui/badge";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/shared/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select";
import { Separator } from "@/shared/components/ui/separator";
import type { PromptTemplate, PromptVariable } from "../types";
import { usePromptGenerator } from "../hooks/use-prompt-generator";
import { cn } from "@/shared/lib/utils";

const CATEGORY_LABELS: Record<string, string> = {
  architecture: "Arhitectură",
  legal: "Legal",
  technical: "Tehnic",
  administrative: "Administrativ",
  gis: "GIS",
  bim: "BIM",
  rendering: "Vizualizare",
  procurement: "Achiziții",
  general: "General",
};

const TARGET_LABELS: Record<string, string> = {
  text: "Text",
  image: "Imagine",
  code: "Cod",
  review: "Review",
  rewrite: "Rescriere",
};

type ViewMode = "templates" | "compose" | "history";

export function PromptGeneratorModule() {
  const {
    allTemplates,
    selectedTemplate,
    values,
    composedPrompt,
    history,
    selectTemplate,
    updateValue,
    saveToHistory,
    deleteHistoryEntry,
    clearSelection,
  } = usePromptGenerator();

  const [viewMode, setViewMode] = useState<ViewMode>("templates");
  const [copied, setCopied] = useState(false);
  const [saved, setSaved] = useState(false);
  const [filterCategory, setFilterCategory] = useState<string>("all");
  const [filterTarget, setFilterTarget] = useState<string>("all");
  const [searchQuery, setSearchQuery] = useState("");

  const handleSelectTemplate = (template: PromptTemplate) => {
    selectTemplate(template);
    setViewMode("compose");
  };

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(composedPrompt);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      /* silent */
    }
  };

  const handleSave = async () => {
    await saveToHistory();
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };

  const handleBack = () => {
    clearSelection();
    setViewMode("templates");
  };

  const filteredTemplates = allTemplates.filter((t) => {
    if (filterCategory !== "all" && t.category !== filterCategory) return false;
    if (filterTarget !== "all" && t.targetAiType !== filterTarget) return false;
    if (searchQuery) {
      const q = searchQuery.toLowerCase();
      return (
        t.name.toLowerCase().includes(q) ||
        t.description.toLowerCase().includes(q) ||
        t.tags.some((tag) => tag.toLowerCase().includes(q)) ||
        (CATEGORY_LABELS[t.category] ?? "").toLowerCase().includes(q)
      );
    }
    return true;
  });

  const usedCategories = [...new Set(allTemplates.map((t) => t.category))];
  const usedTargets = [...new Set(allTemplates.map((t) => t.targetAiType))];

  return (
    <div className="space-y-6">
      {/* Navigation */}
      <div className="flex items-center gap-2">
        <Button
          variant={viewMode === "templates" ? "default" : "outline"}
          size="sm"
          onClick={() => {
            clearSelection();
            setViewMode("templates");
          }}
        >
          <Sparkles className="mr-1 h-3.5 w-3.5" /> Șabloane
        </Button>
        <Button
          variant={viewMode === "history" ? "default" : "outline"}
          size="sm"
          onClick={() => setViewMode("history")}
        >
          <History className="mr-1 h-3.5 w-3.5" /> Istoric ({history.length})
        </Button>
      </div>

      {/* Template browser */}
      {viewMode === "templates" && (
        <div className="space-y-4">
          <div className="flex flex-wrap items-center gap-3">
            <div className="relative min-w-[200px] flex-1">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Caută șabloane..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9"
              />
            </div>
            <Select value={filterCategory} onValueChange={setFilterCategory}>
              <SelectTrigger className="w-[160px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Toate categoriile</SelectItem>
                {usedCategories.map((cat) => (
                  <SelectItem key={cat} value={cat}>
                    {CATEGORY_LABELS[cat] ?? cat}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={filterTarget} onValueChange={setFilterTarget}>
              <SelectTrigger className="w-[140px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Toate tipurile</SelectItem>
                {usedTargets.map((t) => (
                  <SelectItem key={t} value={t}>
                    {TARGET_LABELS[t] ?? t}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {allTemplates.filter((t) => t.targetAiType === "image").length >
              0 && (
              <Button
                variant={filterTarget === "image" ? "default" : "outline"}
                size="sm"
                onClick={() =>
                  setFilterTarget(filterTarget === "image" ? "all" : "image")
                }
              >
                <Image className="mr-1 h-3.5 w-3.5" /> Imagine
              </Button>
            )}
          </div>

          {filteredTemplates.length === 0 ? (
            <p className="py-8 text-center text-sm text-muted-foreground">
              Niciun șablon găsit pentru &ldquo;{searchQuery}&rdquo;.
            </p>
          ) : (
            <div className="grid gap-3 sm:grid-cols-2">
              {filteredTemplates.map((template) => (
                <Card
                  key={template.id}
                  className="cursor-pointer transition-colors hover:border-primary/50 hover:bg-accent/30"
                  onClick={() => handleSelectTemplate(template)}
                >
                  <CardHeader className="pb-2">
                    <div className="flex items-center gap-2">
                      <CardTitle className="text-sm">{template.name}</CardTitle>
                      <Badge variant="outline" className="text-[10px]">
                        {TARGET_LABELS[template.targetAiType]}
                      </Badge>
                    </div>
                    <CardDescription className="text-xs">
                      {template.description}
                    </CardDescription>
                  </CardHeader>
                  <CardContent className="pt-0">
                    <div className="flex flex-wrap gap-1">
                      <Badge variant="secondary" className="text-[10px]">
                        {CATEGORY_LABELS[template.category] ??
                          template.category}
                      </Badge>
                      <Badge variant="secondary" className="text-[10px]">
                        {template.variables.length} variabile
                      </Badge>
                      <Badge variant="secondary" className="text-[10px]">
                        {template.blocks.length} blocuri
                      </Badge>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Composition view */}
      {viewMode === "compose" && selectedTemplate && (
        <div className="space-y-6">
          <div className="flex items-center gap-3">
            <Button variant="ghost" size="sm" onClick={handleBack}>
              <ArrowLeft className="mr-1 h-3.5 w-3.5" /> Înapoi
            </Button>
            <div>
              <h3 className="font-semibold">{selectedTemplate.name}</h3>
              <p className="text-xs text-muted-foreground">
                {selectedTemplate.description}
              </p>
            </div>
          </div>

          <div className="grid gap-6 lg:grid-cols-2">
            {/* Variable form */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Variabile</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                {selectedTemplate.variables.map((variable) => (
                  <VariableField
                    key={variable.id}
                    variable={variable}
                    value={values[variable.id]}
                    onChange={(val) => updateValue(variable.id, val)}
                  />
                ))}
              </CardContent>
            </Card>

            {/* Output */}
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <h3 className="text-sm font-semibold">Prompt compus</h3>
                <div className="flex gap-1.5">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleSave}
                    disabled={!composedPrompt}
                  >
                    <Save className="mr-1 h-3.5 w-3.5" />
                    {saved ? "Salvat!" : "Salvează"}
                  </Button>
                  <Button
                    size="sm"
                    onClick={handleCopy}
                    disabled={!composedPrompt}
                  >
                    {copied ? (
                      <Check className="mr-1 h-3.5 w-3.5" />
                    ) : (
                      <Copy className="mr-1 h-3.5 w-3.5" />
                    )}
                    {copied ? "Copiat!" : "Copiază"}
                  </Button>
                </div>
              </div>
              <div className="min-h-[300px] whitespace-pre-wrap rounded-lg border bg-muted/30 p-4 text-sm">
                {composedPrompt || (
                  <span className="text-muted-foreground italic">
                    Completează variabilele pentru a genera promptul...
                  </span>
                )}
              </div>
              <div className="flex flex-wrap gap-1.5">
                <Badge variant="outline" className="text-[10px]">
                  Output: {selectedTemplate.outputMode}
                </Badge>
                <Badge variant="outline" className="text-[10px]">
                  Blocuri: {selectedTemplate.blocks.length}
                </Badge>
                <Badge variant="outline" className="text-[10px]">
                  Caractere: {composedPrompt.length}
                </Badge>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* History view */}
      {viewMode === "history" && (
        <div className="space-y-3">
          {history.length === 0 ? (
            <p className="py-8 text-center text-sm text-muted-foreground">
              Niciun prompt salvat în istoric.
            </p>
          ) : (
            history.map((entry) => (
              <Card key={entry.id} className="group">
                <CardContent className="p-4">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2">
                        <p className="text-sm font-medium">
                          {entry.templateName}
                        </p>
                        <Badge variant="outline" className="text-[10px]">
                          {entry.outputMode}
                        </Badge>
                      </div>
                      <p className="mt-1 text-xs text-muted-foreground">
                        {new Date(entry.createdAt).toLocaleString("ro-RO")} —{" "}
                        {entry.composedPrompt.length} caractere
                      </p>
                      <pre className="mt-2 max-h-24 overflow-hidden truncate text-xs text-muted-foreground">
                        {entry.composedPrompt.slice(0, 200)}...
                      </pre>
                    </div>
                    <div className="flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
                      <CopyHistoryButton text={entry.composedPrompt} />
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-7 w-7 text-destructive"
                        onClick={() => deleteHistoryEntry(entry.id)}
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))
          )}
        </div>
      )}
    </div>
  );
}

function VariableField({
  variable,
  value,
  onChange,
}: {
  variable: PromptVariable;
  value: unknown;
  onChange: (val: unknown) => void;
}) {
  const strVal = value !== undefined && value !== null ? String(value) : "";

  return (
    <div>
      <Label
        className={cn(
          variable.required &&
            'after:content-["*"] after:ml-0.5 after:text-destructive',
        )}
      >
        {variable.label}
      </Label>
      {variable.helperText && (
        <p className="text-[11px] text-muted-foreground">
          {variable.helperText}
        </p>
      )}

      {(variable.type === "text" || variable.type === "number") && (
        <Input
          type={variable.type === "number" ? "number" : "text"}
          value={strVal}
          onChange={(e) =>
            onChange(
              variable.type === "number"
                ? Number(e.target.value)
                : e.target.value,
            )
          }
          placeholder={variable.placeholder}
          className="mt-1"
        />
      )}

      {(variable.type === "select" ||
        variable.type === "tone-selector" ||
        variable.type === "company-selector") &&
        variable.options && (
          <Select value={strVal} onValueChange={onChange}>
            <SelectTrigger className="mt-1">
              <SelectValue placeholder="Selectează..." />
            </SelectTrigger>
            <SelectContent>
              {variable.options.map((opt) => (
                <SelectItem key={opt.value} value={opt.value}>
                  {opt.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        )}

      {variable.type === "boolean" && (
        <div className="mt-1 flex items-center gap-2">
          <input
            type="checkbox"
            checked={!!value}
            onChange={(e) => onChange(e.target.checked)}
            className="h-4 w-4 rounded accent-primary"
          />
          <span className="text-sm text-muted-foreground">
            {variable.placeholder ?? "Da/Nu"}
          </span>
        </div>
      )}

      {variable.type === "multi-select" && variable.options && (
        <div className="mt-1 flex flex-wrap gap-1.5">
          {variable.options.map((opt) => {
            const selected =
              Array.isArray(value) && (value as string[]).includes(opt.value);
            return (
              <button
                key={opt.value}
                type="button"
                onClick={() => {
                  const arr = Array.isArray(value)
                    ? [...(value as string[])]
                    : [];
                  if (selected) onChange(arr.filter((v) => v !== opt.value));
                  else onChange([...arr, opt.value]);
                }}
                className={cn(
                  "rounded-full border px-2.5 py-0.5 text-xs transition-colors",
                  selected
                    ? "border-primary bg-primary text-primary-foreground"
                    : "hover:bg-accent",
                )}
              >
                {opt.label}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

function CopyHistoryButton({ text }: { text: string }) {
  const [copied, setCopied] = useState(false);
  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch {
      /* silent */
    }
  };
  return (
    <Button
      variant="ghost"
      size="icon"
      className="h-7 w-7"
      onClick={handleCopy}
    >
      {copied ? (
        <Check className="h-3.5 w-3.5 text-green-500" />
      ) : (
        <Copy className="h-3.5 w-3.5" />
      )}
    </Button>
  );
}
