"use client";

import { useEffect, useMemo, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Plus, Edit, Trash2, GripVertical, Filter, Layout } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { deleteCustomFieldAction, saveCustomFieldAction } from "@/lib/admin-actions";
import type { AdminCustomFieldItem, AdminSelectOption } from "@/lib/admin-db";

const fieldTypeLabels: Record<string, string> = {
  boolean: "Да/Не",
  checkbox: "Чекбокс",
  date: "Дата",
  multiselect: "Множествен избор",
  number: "Число",
  radio: "Радио бутони",
  select: "Падащо меню",
  text: "Текст",
  textarea: "Текстово поле",
};

const defaultSections = [
  "Основни",
  "Локация",
  "Характеристики",
  "Удобства",
  "Правен статус",
  "Енергийна ефективност",
];

interface AdminCustomFieldsProps {
  items: AdminCustomFieldItem[];
  propertyTypes: AdminSelectOption[];
}

const emptyForm = {
  code: "",
  defaultValue: "",
  fieldType: "text",
  helpText: "",
  id: "",
  isRequired: false,
  isVisibleInDetail: true,
  isVisibleInListing: false,
  label: "",
  options: "",
  propertyTypeId: "",
  section: defaultSections[0],
  showInFilter: false,
  sortOrder: "10",
};

export default function AdminCustomFields({
  items,
  propertyTypes,
}: AdminCustomFieldsProps) {
  const [filterType, setFilterType] = useState("all");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [form, setForm] = useState({
    ...emptyForm,
    propertyTypeId: propertyTypes[0]?.id || "",
  });
  const [isPending, startTransition] = useTransition();
  const router = useRouter();

  useEffect(() => {
    if (!dialogOpen) {
      setForm({
        ...emptyForm,
        propertyTypeId: propertyTypes[0]?.id || "",
      });
    }
  }, [dialogOpen, propertyTypes]);

  const filtered =
    filterType === "all"
      ? items
      : items.filter((field) => field.propertyTypeId === filterType);

  const grouped = useMemo(() => {
    const sectionOrder = [
      ...defaultSections,
      ...filtered
        .map((item) => item.section)
        .filter((section) => !defaultSections.includes(section)),
    ];

    return sectionOrder
      .map((section) => ({
        fields: filtered.filter((field) => field.section === section),
        section,
      }))
      .filter((group) => group.fields.length > 0);
  }, [filtered]);

  const supportsOptions = ["select", "multiselect", "radio", "checkbox"].includes(
    form.fieldType,
  );

  const openEdit = (field: AdminCustomFieldItem) => {
    setForm({
      code: field.code,
      defaultValue: field.defaultValue,
      fieldType: field.fieldType,
      helpText: field.helpText,
      id: field.id,
      isRequired: field.isRequired,
      isVisibleInDetail: field.isVisibleInDetail,
      isVisibleInListing: field.isVisibleInListing,
      label: field.label,
      options: field.options.join(", "),
      propertyTypeId: field.propertyTypeId,
      section: field.section,
      showInFilter: field.showInFilter,
      sortOrder: String(field.sortOrder),
    });
    setDialogOpen(true);
  };

  const handleSave = () => {
    startTransition(async () => {
      const result = await saveCustomFieldAction({
        code: form.code,
        defaultValue: form.defaultValue,
        fieldType: form.fieldType,
        helpText: form.helpText,
        id: form.id || undefined,
        isRequired: form.isRequired,
        isVisibleInDetail: form.isVisibleInDetail,
        isVisibleInListing: form.isVisibleInListing,
        label: form.label,
        options: form.options.split(",").map((item) => item.trim()).filter(Boolean),
        propertyTypeId: form.propertyTypeId,
        section: form.section,
        showInFilter: form.showInFilter,
        sortOrder: form.sortOrder,
      });

      if (!result.ok) {
        window.alert(result.error || "Неуспешно записване.");
        return;
      }

      setDialogOpen(false);
      router.refresh();
    });
  };

  const handleDelete = (id: string) => {
    if (!window.confirm("Сигурен ли си, че искаш да деактивираш това поле?")) {
      return;
    }

    startTransition(async () => {
      const result = await deleteCustomFieldAction(id);
      if (!result.ok) {
        window.alert(result.error || "Неуспешно изтриване.");
        return;
      }

      router.refresh();
    });
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <h1 className="text-2xl font-bold text-foreground">Custom Fields</h1>
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger asChild>
            <Button
              onClick={() =>
                setForm({
                  ...emptyForm,
                  propertyTypeId: propertyTypes[0]?.id || "",
                })
              }
            >
              <Plus className="h-4 w-4 mr-1" /> Ново поле
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-lg max-h-[80vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>{form.id ? "Редакция на поле" : "Ново custom поле"}</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <div>
                <Label>Име на полето</Label>
                <Input
                  placeholder="напр. Гледка към морето"
                  value={form.label}
                  onChange={(e) => setForm((prev) => ({ ...prev, label: e.target.value }))}
                />
              </div>
              <div>
                <Label>Ключ</Label>
                <Input
                  placeholder="напр. sea-view"
                  value={form.code}
                  onChange={(e) => setForm((prev) => ({ ...prev, code: e.target.value }))}
                />
              </div>
              <div>
                <Label>Тип имот</Label>
                <Select
                  value={form.propertyTypeId}
                  onValueChange={(value) =>
                    setForm((prev) => ({ ...prev, propertyTypeId: value }))
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Избери тип имот" />
                  </SelectTrigger>
                  <SelectContent>
                    {propertyTypes.map((type) => (
                      <SelectItem key={type.id} value={type.id}>
                        {type.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>Тип на полето</Label>
                <Select
                  value={form.fieldType}
                  onValueChange={(value) =>
                    setForm((prev) => ({ ...prev, fieldType: value }))
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Избери тип" />
                  </SelectTrigger>
                  <SelectContent>
                    {Object.entries(fieldTypeLabels).map(([key, label]) => (
                      <SelectItem key={key} value={key}>
                        {label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>Секция</Label>
                <Input
                  placeholder="напр. Удобства"
                  value={form.section}
                  onChange={(e) => setForm((prev) => ({ ...prev, section: e.target.value }))}
                />
              </div>
              {supportsOptions ? (
                <div>
                  <Label>Опции</Label>
                  <Input
                    placeholder="Стойност 1, Стойност 2, ..."
                    value={form.options}
                    onChange={(e) => setForm((prev) => ({ ...prev, options: e.target.value }))}
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    Разделени със запетая
                  </p>
                </div>
              ) : null}
              <div>
                <Label>Стойност по подразбиране</Label>
                <Input
                  placeholder="по избор"
                  value={form.defaultValue}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, defaultValue: e.target.value }))
                  }
                />
              </div>
              <div>
                <Label>Помощен текст</Label>
                <Input
                  placeholder="Допълнителна информация за потребителя"
                  value={form.helpText}
                  onChange={(e) => setForm((prev) => ({ ...prev, helpText: e.target.value }))}
                />
              </div>
              <div>
                <Label>Ред</Label>
                <Input
                  placeholder="10"
                  type="number"
                  value={form.sortOrder}
                  onChange={(e) => setForm((prev) => ({ ...prev, sortOrder: e.target.value }))}
                />
              </div>
              <div className="flex items-center justify-between">
                <Label>Задължително поле</Label>
                <Switch
                  checked={form.isRequired}
                  onCheckedChange={(checked) =>
                    setForm((prev) => ({ ...prev, isRequired: Boolean(checked) }))
                  }
                />
              </div>
              <div className="flex items-center justify-between">
                <Label>Показвай във филтри</Label>
                <Switch
                  checked={form.showInFilter}
                  onCheckedChange={(checked) =>
                    setForm((prev) => ({ ...prev, showInFilter: Boolean(checked) }))
                  }
                />
              </div>
              <div className="flex items-center justify-between">
                <Label>Показвай в листинг</Label>
                <Switch
                  checked={form.isVisibleInListing}
                  onCheckedChange={(checked) =>
                    setForm((prev) => ({
                      ...prev,
                      isVisibleInListing: Boolean(checked),
                    }))
                  }
                />
              </div>
              <div className="flex items-center justify-between">
                <Label>Показвай в детайлна страница</Label>
                <Switch
                  checked={form.isVisibleInDetail}
                  onCheckedChange={(checked) =>
                    setForm((prev) => ({
                      ...prev,
                      isVisibleInDetail: Boolean(checked),
                    }))
                  }
                />
              </div>
              <div className="flex justify-end gap-2">
                <Button variant="outline" onClick={() => setDialogOpen(false)}>
                  Отказ
                </Button>
                <Button disabled={isPending} onClick={handleSave}>
                  {form.id ? "Запази" : "Създай"}
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <div className="flex items-center gap-3">
        <Label className="text-sm whitespace-nowrap">Филтър по тип:</Label>
        <Select value={filterType} onValueChange={setFilterType}>
          <SelectTrigger className="w-56">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Всички типове</SelectItem>
            {propertyTypes.map((type) => (
              <SelectItem key={type.id} value={type.id}>
                {type.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {grouped.map(({ section, fields }) => (
        <Card key={section}>
          <CardHeader>
            <CardTitle className="text-base">{section}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-2">
            {fields.map((field) => (
              <div
                key={field.id}
                className="flex items-center gap-3 p-3 rounded-lg bg-muted/50 group"
              >
                <GripVertical className="h-4 w-4 text-muted-foreground cursor-grab shrink-0" />
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className="text-sm font-medium text-foreground">
                      {field.label}
                    </span>
                    <Badge variant="secondary" className="text-xs">
                      {fieldTypeLabels[field.fieldType] || field.fieldType}
                    </Badge>
                    <Badge variant="outline" className="text-xs">
                      {field.propertyTypeLabel}
                    </Badge>
                    {field.isRequired ? (
                      <Badge variant="destructive" className="text-xs">
                        Задължително
                      </Badge>
                    ) : null}
                    {field.showInFilter ? (
                      <span className="text-xs text-muted-foreground flex items-center gap-1">
                        <Filter className="h-3 w-3" /> Филтър
                      </span>
                    ) : null}
                    {field.isVisibleInDetail ? (
                      <span className="text-xs text-muted-foreground flex items-center gap-1">
                        <Layout className="h-3 w-3" /> Детайл
                      </span>
                    ) : null}
                  </div>
                  <div className="flex flex-wrap gap-2 mt-1 text-xs text-muted-foreground">
                    <span>Код: {field.code}</span>
                    <span>Ред: {field.sortOrder}</span>
                    {field.options.length > 0 ? (
                      <span>Опции: {field.options.join(", ")}</span>
                    ) : null}
                  </div>
                </div>
                <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-7 w-7"
                    onClick={() => openEdit(field)}
                  >
                    <Edit className="h-3 w-3" />
                  </Button>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-7 w-7 text-destructive"
                    onClick={() => handleDelete(field.id)}
                  >
                    <Trash2 className="h-3 w-3" />
                  </Button>
                </div>
              </div>
            ))}
          </CardContent>
        </Card>
      ))}

      {grouped.length === 0 ? (
        <Card>
          <CardContent className="p-6 text-sm text-muted-foreground">
            Няма custom fields за избрания тип имот.
          </CardContent>
        </Card>
      ) : null}
    </div>
  );
}
