import { useState, useEffect, useCallback } from "react";
import { useSearchParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Loader } from "lucide-react";
import { TemplateService } from "@/user-management/services/api/templateService";
import { TemplateResource } from "@/user-management/services/TemplateConfiguration/types/templateTypes";
import { StyleSettingsPage } from "./StyleSettingsPage";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";

export const TemplateSamplePage = ({ unitId }: { unitId?: string }) => {
  const { t } = useTranslation();
  const [searchParams, setSearchParams] = useSearchParams();
  const [templates, setTemplates] = useState<TemplateResource[]>([]);
  const [selectedTemplateId, setSelectedTemplateId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadTemplates();
  }, []);

  const loadTemplates = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await TemplateService.getAllTemplates();
      setTemplates(response.items || []);
      const templateFromUrl = searchParams.get("template");
      const matchedTemplate = response.items?.find(
        (item) => item.id === templateFromUrl,
      );
      if (matchedTemplate) {
        setSelectedTemplateId(matchedTemplate.id);
      } else if (response.items?.length > 0) {
        const firstId = response.items[0].id;
        setSelectedTemplateId(firstId);
        setSearchParams(
          (prev) => {
            const next = new URLSearchParams(prev);
            next.set("template", firstId);
            return next;
          },
          { replace: true },
        );
      }
    } catch (err) {
      setError(t("error.loadingTemplates", "Error loading templates"));
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const handleTemplateChange = (templateId: string) => {
    setSelectedTemplateId(templateId);
    setSearchParams(
      (prev) => {
        const next = new URLSearchParams(prev);
        next.set("template", templateId);
        return next;
      },
      { replace: true },
    );
  };

  const handleBack = () => {
      setSelectedTemplateId(null);
    // If you want to go back to content management, you might need to pass a callback.
    // For now, we just reset selection (or you could navigate back).
    // Since this is directly rendered in ContentManagement, we can keep as is.
    // Alternatively, you could clear the selection to show a "select template" message.
    // We'll just keep the dropdown so user can choose another template.
    // If you need a back button to exit the whole page, add one above.
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <Loader className="h-8 w-8 animate-spin text-purple-600" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-4 bg-red-50 border border-red-200 rounded-lg text-red-700">
        {error}
      </div>
    );
  }

  if (templates.length === 0) {
    return (
      <div className="text-center py-12">
        <p className="text-gray-500 dark:text-gray-400">
          {t("template.noTemplates", "No templates available")}
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Template Selector */}
      <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
        <div className="flex items-center gap-4">
          <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
            {t("template.selectTemplate", "Select Template")}
          </label>
          <Select value={selectedTemplateId || ""} onValueChange={handleTemplateChange}>
            <SelectTrigger className="w-64">
              <SelectValue placeholder={t("template.selectTemplate")} />
            </SelectTrigger>
            <SelectContent>
              {templates.map((template) => (
                <SelectItem key={template.id} value={template.id}>
                  {template.name?.en || template.name?.am}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Style Editor */}
      {selectedTemplateId && unitId ? (
        <StyleSettingsPage
          key={`${unitId}-${selectedTemplateId}`}
          templateId={selectedTemplateId}
          unitId={unitId}
          onBack={handleBack}
        />
      ) : selectedTemplateId && !unitId ? (
        <div className="rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800 dark:border-amber-800 dark:bg-amber-900/20 dark:text-amber-200">
          {t("organization.selectUnit", "Please select a unit to edit style settings.")}
        </div>
      ) : null}
    </div>
  );
};