"use client";

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

interface FormScreenConfigProps {
  screen: BuilderScreen & { template: "form" };
  onUpdate: (updates: Partial<FormScreenDefinition>) => void;
}

export function FormScreenConfig({ screen, onUpdate }: FormScreenConfigProps) {
  const formScreen = screen as FormScreenDefinition;

  const updateField = (index: number, updates: Partial<FormFieldDefinition>) => {
    const newFields = [...(formScreen.fields || [])];
    newFields[index] = { ...newFields[index], ...updates };
    onUpdate({ fields: newFields });
  };

  const updateValidationMessages = (updates: Partial<FormValidationMessages>) => {
    onUpdate({
      validationMessages: {
        ...(formScreen.validationMessages ?? {}),
        ...updates,
      },
    });
  };

  const addField = () => {
    const newField: FormFieldDefinition = {
      id: `field_${Date.now()}`,
      label: "Новое поле",
      placeholder: "Введите значение",
      type: "text",
      required: true,
    };

    onUpdate({
      fields: [...(formScreen.fields || []), newField],
    });
  };

  const removeField = (index: number) => {
    const newFields = formScreen.fields?.filter((_, i) => i !== index) || [];
    onUpdate({ fields: newFields });
  };

  return (
    <div className="space-y-4">
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <h3 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">Поля формы</h3>
          <Button onClick={addField} variant="outline" className="h-8 w-8 p-0 flex items-center justify-center">
            <Plus className="h-4 w-4" />
          </Button>
        </div>

        {formScreen.fields?.map((field, index) => (
          <div key={index} className="space-y-2 rounded-lg border border-border/50 bg-muted/5 p-3">
            <div className="flex items-center justify-between gap-2">
              <span className="text-xs font-semibold uppercase text-muted-foreground">
                Поле {index + 1}
              </span>
              <Button
                variant="ghost"
                className="h-8 px-2 text-destructive hover:bg-destructive/10"
                onClick={() => removeField(index)}
              >
                <Trash2 className="h-3 w-3 mr-1" />
                Удалить
              </Button>
            </div>

            <div className="grid grid-cols-2 gap-3">
              <label className="flex flex-col gap-1">
                <span className="text-sm font-medium text-muted-foreground">ID поля</span>
                <TextInput value={field.id} onChange={(event) => updateField(index, { id: event.target.value })} />
              </label>
              <label className="flex flex-col gap-1">
                <span className="text-sm font-medium text-muted-foreground">Тип</span>
                <select
                  className="rounded-lg border border-border bg-background px-3 py-2 text-sm"
                  value={field.type ?? "text"}
                  onChange={(event) => updateField(index, { type: event.target.value as FormFieldDefinition["type"] })}
                >
                  <option value="text">Текст</option>
                  <option value="email">E-mail</option>
                  <option value="tel">Телефон</option>
                </select>
              </label>
            </div>

            <label className="flex flex-col gap-1">
              <span className="text-sm font-medium text-muted-foreground">Метка поля</span>
              <TextAreaInput
                value={field.label ?? ""}
                onChange={(event) => updateField(index, { label: event.target.value })}
                rows={2}
                className="resize-y"
              />
            </label>

            <label className="flex flex-col gap-1">
              <span className="text-sm font-medium text-muted-foreground">Placeholder</span>
              <TextAreaInput
                value={field.placeholder ?? ""}
                onChange={(event) => updateField(index, { placeholder: event.target.value })}
                rows={2}
                className="resize-y"
              />
            </label>

            <div className="pt-2">
              <label className="flex items-center gap-2 text-sm text-muted-foreground">
                <input
                  type="checkbox"
                  checked={field.required ?? false}
                  onChange={(event) => updateField(index, { required: event.target.checked })}
                />
                Обязательно для заполнения
              </label>
            </div>

          </div>
        ))}

        {(!formScreen.fields || formScreen.fields.length === 0) && (
          <div className="rounded-lg border border-dashed border-border/60 p-4 text-center text-sm text-muted-foreground">
            Пока нет полей. Добавьте хотя бы одно, чтобы форма работала.
          </div>
        )}
      </div>

      <div className="space-y-3">
        <h4 className="text-sm font-semibold text-foreground">Сообщения валидации</h4>
        <div className="space-y-4 text-xs">
          <div className="rounded-lg border border-border/60 bg-muted/20 p-3">
            <label className="flex flex-col gap-2 text-muted-foreground">
              <div>
                <span className="font-medium">Обязательное поле</span>
                <p className="text-xs mt-1 text-muted-foreground/80">
                  Доступна переменная: <code className="bg-muted px-1 rounded">{`{field}`}</code> - название поля
                </p>
              </div>
              <TextAreaInput
                placeholder="Пример: Поле {field} обязательно"
                value={formScreen.validationMessages?.required ?? ""}
                onChange={(event) => updateValidationMessages({ required: event.target.value || undefined })}
                rows={2}
                className="resize-y"
              />
            </label>
          </div>
          
        </div>
      </div>
    </div>
  );
}
