"use client";

import { useState, useMemo } from "react";
import { ChevronDown, ChevronUp, Eye, EyeOff, FileText } from "lucide-react";
import type {
  PromptSections,
  VoiceAgentConfig,
} from "@/lib/types/voice-agent.types";
import { INDUSTRY_TEMPLATES } from "@/lib/services/voice-agent-prompt-builder";

interface StructuredPromptEditorProps {
  sections: PromptSections;
  onChange: (sections: PromptSections) => void;
  config: VoiceAgentConfig;
  t: Record<string, string>;
}

type SectionKey = keyof PromptSections;

export default function StructuredPromptEditor({
  sections,
  onChange,
  config,
  t,
}: StructuredPromptEditorProps) {
  const [expandedSection, setExpandedSection] = useState<string | null>(
    "identity",
  );
  const [showPreview, setShowPreview] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<string>("");

  const sectionConfig = useMemo(
    () => [
      {
        key: "identity" as const,
        label: t.vaPromptIdentity,
        desc: t.vaPromptIdentityDesc,
        placeholder: t.vaPromptIdentityPlaceholder,
      },
      {
        key: "style" as const,
        label: t.vaPromptStyle,
        desc: t.vaPromptStyleDesc,
        placeholder: t.vaPromptStylePlaceholder,
      },
      {
        key: "responseGuidelines" as const,
        label: t.vaPromptResponseGuidelines,
        desc: t.vaPromptResponseGuidelinesDesc,
        placeholder: t.vaPromptResponseGuidelinesPlaceholder,
      },
      {
        key: "taskFlow" as const,
        label: t.vaPromptTaskFlow,
        desc: t.vaPromptTaskFlowDesc,
        placeholder: t.vaPromptTaskFlowPlaceholder,
      },
      {
        key: "guardrails" as const,
        label: t.vaPromptGuardrails,
        desc: t.vaPromptGuardrailsDesc,
        placeholder: t.vaPromptGuardrailsPlaceholder,
      },
    ],
    [t],
  );

  const handleSectionChange = (key: SectionKey, value: string) => {
    onChange({ ...sections, [key]: value });
  };

  const handleTemplateSelect = (templateId: string) => {
    setSelectedTemplate(templateId);
    if (!templateId) return;
    const template = INDUSTRY_TEMPLATES.find((t) => t.id === templateId);
    if (template) {
      onChange({ ...template.sections });
    }
  };

  // Build preview using same logic as voice-agent-prompt-builder
  const previewPrompt = useMemo(() => {
    const parts: string[] = [];
    if (sections.identity)
      parts.push(`<identity>\n${sections.identity}\n</identity>`);
    if (sections.style) parts.push(`<style>\n${sections.style}\n</style>`);
    if (sections.responseGuidelines)
      parts.push(
        `<response_guidelines>\n${sections.responseGuidelines}\n</response_guidelines>`,
      );
    if (sections.taskFlow) parts.push(`<task>\n${sections.taskFlow}\n</task>`);
    if (sections.guardrails)
      parts.push(`<guardrails>\n${sections.guardrails}\n</guardrails>`);
    return parts.join("\n\n") || "(No sections configured yet)";
  }, [sections]);

  const charCount = (key: SectionKey) => (sections[key] || "").length;

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-sm font-medium text-gray-900">
            {t.vaPromptSections}
          </h3>
          <p className="text-xs text-gray-500 mt-0.5">
            {t.vaPromptSectionsDesc}
          </p>
        </div>
      </div>

      {/* Template Selector */}
      <div className="flex items-center gap-3">
        <FileText className="w-4 h-4 text-gray-400 shrink-0" />
        <select
          value={selectedTemplate}
          onChange={(e) => handleTemplateSelect(e.target.value)}
          className="flex-1 text-sm border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
        >
          <option value="">{t.vaPromptTemplateSelect}</option>
          {INDUSTRY_TEMPLATES.map((tmpl) => (
            <option key={tmpl.id} value={tmpl.id}>
              {config.language === "ar" ? tmpl.name.ar : tmpl.name.en}
            </option>
          ))}
        </select>
      </div>

      {/* Accordion Sections */}
      <div className="border border-gray-200 rounded-lg divide-y divide-gray-200">
        {sectionConfig.map(({ key, label, desc, placeholder }) => {
          const isExpanded = expandedSection === key;
          const chars = charCount(key);
          return (
            <div key={key}>
              <button
                type="button"
                onClick={() => setExpandedSection(isExpanded ? null : key)}
                className="w-full flex items-center justify-between px-4 py-3 text-left hover:bg-gray-50 transition"
              >
                <div className="flex items-center gap-2">
                  <span className="text-sm font-medium text-gray-900">
                    {label}
                  </span>
                  {chars > 0 && (
                    <span className="text-xs text-gray-400">{chars} chars</span>
                  )}
                </div>
                {isExpanded ? (
                  <ChevronUp className="w-4 h-4 text-gray-400" />
                ) : (
                  <ChevronDown className="w-4 h-4 text-gray-400" />
                )}
              </button>
              {isExpanded && (
                <div className="px-4 pb-4">
                  <p className="text-xs text-gray-500 mb-2">{desc}</p>
                  <textarea
                    value={sections[key] || ""}
                    onChange={(e) => handleSectionChange(key, e.target.value)}
                    placeholder={placeholder}
                    rows={4}
                    maxLength={2000}
                    className="w-full text-sm border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-y"
                  />
                  <div className="text-xs text-gray-400 text-right mt-1">
                    {chars}/2000
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Preview Toggle */}
      <button
        type="button"
        onClick={() => setShowPreview(!showPreview)}
        className="flex items-center gap-2 text-sm text-blue-600 hover:text-blue-700 font-medium"
      >
        {showPreview ? (
          <EyeOff className="w-4 h-4" />
        ) : (
          <Eye className="w-4 h-4" />
        )}
        {t.vaPromptPreview}
      </button>

      {showPreview && (
        <pre className="bg-gray-50 border border-gray-200 rounded-lg p-4 text-xs text-gray-700 overflow-x-auto whitespace-pre-wrap max-h-96">
          {previewPrompt}
        </pre>
      )}
    </div>
  );
}
