"use client";

import React from "react";
import { Button } from "@/components/ui/button";
import { TextInput } from "@/components/ui/TextInput/TextInput";
import { Trash2, Plus } from "lucide-react";
import type { BuilderScreen } from "@/lib/admin/builder/types";
import type { LoadersScreenDefinition } from "@/lib/funnel/types";

interface LoadersScreenConfigProps {
  screen: BuilderScreen & { template: "loaders" };
  onUpdate: (updates: Partial<LoadersScreenDefinition>) => void;
}

export function LoadersScreenConfig({ screen, onUpdate }: LoadersScreenConfigProps) {
  const updateProgressbars = (updates: Partial<LoadersScreenDefinition["progressbars"]>) => {
    onUpdate({
      progressbars: {
        items: screen.progressbars?.items || [],
        transitionDuration: screen.progressbars?.transitionDuration || 5000,
        ...updates,
      },
    });
  };

  const addProgressbarItem = () => {
    const currentItems = screen.progressbars?.items || [];
    updateProgressbars({
      items: [
        ...currentItems,
        {
          title: `Step ${currentItems.length + 1}`,
          subtitle: "",
          processingTitle: `Processing step ${currentItems.length + 1}...`,
          processingSubtitle: "",
          completedTitle: `Step ${currentItems.length + 1} completed`,
          completedSubtitle: "",
        },
      ],
    });
  };

  const removeProgressbarItem = (index: number) => {
    const currentItems = screen.progressbars?.items || [];
    updateProgressbars({
      items: currentItems.filter((_, i) => i !== index),
    });
  };

  const updateProgressbarItem = (
    index: number,
    updates: Partial<LoadersScreenDefinition["progressbars"]["items"][0]>
  ) => {
    const currentItems = screen.progressbars?.items || [];
    const updatedItems = currentItems.map((item, i) =>
      i === index ? { ...item, ...updates } : item
    );
    updateProgressbars({ items: updatedItems });
  };

  return (
    <div className="space-y-4">
      <div>
        <h4 className="text-sm font-medium text-slate-700 mb-3">Настройки анимации</h4>
        <TextInput
          label="Длительность анимации (мс)"
          type="number"
          placeholder="5000"
          value={screen.progressbars?.transitionDuration?.toString() || "5000"}
          onChange={(e) => updateProgressbars({ transitionDuration: parseInt(e.target.value) || 5000 })}
        />
      </div>

      <div>
        <div className="flex items-center justify-between mb-3">
          <h4 className="text-sm font-medium text-slate-700">Шаги загрузки</h4>
          <Button
            type="button"
            variant="outline"
            onClick={addProgressbarItem}
            className="flex items-center gap-2 text-sm px-3 py-1"
          >
            <Plus className="w-4 h-4" />
            Добавить шаг
          </Button>
        </div>

        <div className="space-y-4">
          {(screen.progressbars?.items || []).map((item, index) => (
            <div key={index} className="border rounded-lg p-4 space-y-3">
              <div className="flex items-center justify-between">
                <h5 className="text-sm font-medium text-slate-600">Шаг {index + 1}</h5>
                <Button
                  type="button"
                  variant="ghost"
                  onClick={() => removeProgressbarItem(index)}
                  className="text-red-600 hover:text-red-700 text-sm px-2 py-1"
                >
                  <Trash2 className="w-4 h-4" />
                </Button>
              </div>
              
              <div className="grid grid-cols-2 gap-3">
                <TextInput
                  label="Заголовок"
                  placeholder="Step 1"
                  value={item.title || ""}
                  onChange={(e) => updateProgressbarItem(index, { title: e.target.value })}
                />
                <TextInput
                  label="Подзаголовок"
                  placeholder="Описание шага"
                  value={item.subtitle || ""}
                  onChange={(e) => updateProgressbarItem(index, { subtitle: e.target.value })}
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <TextInput
                  label="Текст во время обработки"
                  placeholder="Processing..."
                  value={item.processingTitle || ""}
                  onChange={(e) => updateProgressbarItem(index, { processingTitle: e.target.value })}
                />
                <TextInput
                  label="Подтекст во время обработки"
                  placeholder=""
                  value={item.processingSubtitle || ""}
                  onChange={(e) => updateProgressbarItem(index, { processingSubtitle: e.target.value })}
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <TextInput
                  label="Текст при завершении"
                  placeholder="Completed!"
                  value={item.completedTitle || ""}
                  onChange={(e) => updateProgressbarItem(index, { completedTitle: e.target.value })}
                />
                <TextInput
                  label="Подтекст при завершении"
                  placeholder=""
                  value={item.completedSubtitle || ""}
                  onChange={(e) => updateProgressbarItem(index, { completedSubtitle: e.target.value })}
                />
              </div>
            </div>
          ))}
        </div>

        {(screen.progressbars?.items || []).length === 0 && (
          <div className="text-center py-8 text-slate-500">
            <p>Нет шагов загрузки</p>
            <Button
              type="button"
              variant="outline"
              onClick={addProgressbarItem}
              className="mt-2 text-sm px-3 py-1"
            >
              Добавить первый шаг
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
