import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
} from "@/shared/common/ui/card";
import { FileText, Plus } from "lucide-react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { useState } from "react";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { useTemplate } from "../service/useTemplate";
import { TemplateForm } from "./TemplateForm";
import { toast } from "sonner";
import { Button } from "@/shared/common/ui/button";
import { t } from "i18next";
import i18n from "@/i18n";
import { CreateTemplateTypes } from "../types/templateTypes";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

const TemplateCard = () => {
  const { handleError } = useErrorHandler(t);
  const {
    templates,
    isLoading,
    isError,
    refetch,
    createTemplate,
    updateTemplate,
    isCreatingTemplate,
    isUpdatingTemplate,
  } = useTemplate();

  const lang = i18n.language;
  const [selectedTemplateId, setSelectedTemplateId] = useState<string | null>(
    null
  );
  const [showCreateForm, setShowCreateForm] = useState(false);

  const templateList: CreateTemplateTypes[] = Array.isArray(templates) ? templates : templates?.items || [];
  const selectedTemplate =
    templateList.find((t) => t.id === selectedTemplateId) ?? null;

  return (
    <Card className="bg-gradient-to-br from-primary-50 to-primary-50">
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="flex items-center">
              <FileText className="h-5 w-5 mr-2" />
              {t("contentManagement.letterTemplate")}
            </CardTitle>
            <CardDescription>
              {t("contentManagement.createMsg")}
            </CardDescription>
          </div>
          <Button onClick={() => setShowCreateForm(true)} size="sm">
            <Plus className="h-4 w-4 mr-1" />
            {t("contentManagement.addTemplate")}
          </Button>
        </div>
      </CardHeader>

      <CardContent className="space-y-6">
        {isLoading ? (
          <>
            <Skeleton className="h-10 w-full" />
            <Skeleton className="h-20 w-full" />
          </>
        ) : isError ? (
          <p className="text-sm text-red-600">
            {t("contentManagement.failedToLoadTemplates")}
          </p>
        ) : (
          <>
            {templateList.length > 0 && (
              <Select
                onValueChange={(value) => {
                  setSelectedTemplateId(value);
                  setShowCreateForm(false);
                }}
                value={selectedTemplateId ?? undefined}
              >
                <SelectTrigger>
                  <SelectValue placeholder={t("contentManagement.selectTemplate")} />
                </SelectTrigger>
                <SelectContent>
                  {templateList.map((template) => (
                    <SelectItem key={template.id!} value={template.id!}>
                      {lang === "en" ? template.name.en : template.name.am}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}

            {(selectedTemplate || showCreateForm) && (
              <TemplateForm
                isSubmitting={isCreatingTemplate || isUpdatingTemplate}
                template={selectedTemplate}
                onCancel={() => {
                  setShowCreateForm(false);
                  setSelectedTemplateId(null);
                }}
                onSubmitCreate={(values) => {
                  if (selectedTemplate?.id) {
                    updateTemplate(
                      { id: selectedTemplate.id, template: values },
                      {
                        onSuccess: () => {
                          toast.success(t("contentManagement.updateTemplate"));
                          refetch();
                          setShowCreateForm(false);
                        },
                        onError: (error) => {
                          handleError(error);
                        },
                      }
                    );
                  } else {
                    createTemplate(values, {
                      onSuccess: (newTemplate: any) => {
                        toast.success(
                          `${values.name.en} ${t("contentManagement.templateSuccessMsg")}`
                        );
                        refetch();
                        setShowCreateForm(false);
                        // setSelectedTemplateId(newTemplate.id);
                      },
                      onError: (error) => {
                        handleError(error);
                      },
                    });
                  }
                }}
              />
            )}
          </>
        )}
      </CardContent>
    </Card>
  );
};

export default TemplateCard;
