import { createFileRoute } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useState, useEffect, useMemo } from "react";
import { Search, Plus, Edit, Trash2, Tag, Package } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";

export const Route = createFileRoute("/_authenticated/product-types")({
  head: () => ({
    meta: [
      { title: "Product Types — Niyamah Electric & Hardware" },
      { name: "description", content: "Product type management" },
    ],
  }),
  component: ProductTypesPage,
});

type ProductTypeRow = {
  id: string;
  name: string;
  name_bn: string;
  icon: string;
  status: string;
  deleted_at: string | null;
  created_at: string;
  updated_at: string;
  product_count?: number;
};

function ProductTypesPage() {
  const { tr, lang } = useLanguage();
  const [types, setTypes] = useState<ProductTypeRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");

  // Modal state
  const [modalOpen, setModalOpen] = useState(false);
  const [editingType, setEditingType] = useState<ProductTypeRow | null>(null);
  const [formName, setFormName] = useState("");
  const [formNameBn, setFormNameBn] = useState("");
  const [formIcon, setFormIcon] = useState("");
  const [formStatus, setFormStatus] = useState("active");
  const [saving, setSaving] = useState(false);

  // Delete confirm
  const [deleteTarget, setDeleteTarget] = useState<ProductTypeRow | null>(null);

  const fetchTypes = async () => {
    setLoading(true);
    const { data: typesData } = await supabase
      .from("product_types")
      .select("*")
      .is("deleted_at", null)
      .order("created_at", { ascending: true });

    if (typesData) {
      // Get product counts per type
      const { data: products } = await supabase
        .from("products")
        .select("product_type_id")
        .eq("is_deleted", false);

      const countMap: Record<string, number> = {};
      (products || []).forEach((p) => {
        if (p.product_type_id) {
          countMap[p.product_type_id] = (countMap[p.product_type_id] || 0) + 1;
        }
      });

      setTypes(
        typesData.map((t) => ({ ...t, product_count: countMap[t.id] || 0 }))
      );
    }
    setLoading(false);
  };

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

  const filtered = useMemo(() => {
    return types.filter((t) => {
      const s = search.toLowerCase();
      const matchSearch =
        !search ||
        t.name.toLowerCase().includes(s) ||
        t.name_bn.includes(search);
      const matchStatus =
        statusFilter === "all" || t.status === statusFilter;
      return matchSearch && matchStatus;
    });
  }, [types, search, statusFilter]);

  const openAddModal = () => {
    setEditingType(null);
    setFormName("");
    setFormNameBn("");
    setFormIcon("📦");
    setFormStatus("active");
    setModalOpen(true);
  };

  const openEditModal = (t: ProductTypeRow) => {
    setEditingType(t);
    setFormName(t.name);
    setFormNameBn(t.name_bn);
    setFormIcon(t.icon);
    setFormStatus(t.status);
    setModalOpen(true);
  };

  const handleSave = async () => {
    if (!formName.trim()) {
      toast.error(lang === "bn" ? "টাইপ নাম দিন" : "Type name is required");
      return;
    }

    // Check duplicate
    const duplicate = types.find(
      (t) =>
        t.name.toLowerCase() === formName.trim().toLowerCase() &&
        t.id !== editingType?.id
    );
    if (duplicate) {
      toast.error(
        lang === "bn"
          ? "এই নামে ইতোমধ্যে Product Type আছে"
          : "A product type with this name already exists"
      );
      return;
    }

    setSaving(true);

    if (editingType) {
      const { error } = await supabase
        .from("product_types")
        .update({
          name: formName.trim(),
          name_bn: formNameBn.trim(),
          icon: formIcon.trim(),
          status: formStatus,
        })
        .eq("id", editingType.id);

      if (error) {
        toast.error(lang === "bn" ? "আপডেট করা যায়নি" : "Failed to update");
      } else {
        toast.success(
          lang === "bn" ? "Product Type আপডেট হয়েছে" : "Product type updated"
        );
      }
    } else {
      const { error } = await supabase.from("product_types").insert({
        name: formName.trim(),
        name_bn: formNameBn.trim(),
        icon: formIcon.trim(),
        status: formStatus,
      });

      if (error) {
        toast.error(lang === "bn" ? "যোগ করা যায়নি" : "Failed to add");
      } else {
        toast.success(
          lang === "bn" ? "নতুন Product Type যোগ হয়েছে" : "Product type added"
        );
      }
    }

    setSaving(false);
    setModalOpen(false);
    fetchTypes();
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;

    if ((deleteTarget.product_count || 0) > 0) {
      toast.error(
        lang === "bn"
          ? "এই Product Type এর সাথে Product যুক্ত আছে, আগে Product update করুন"
          : "This product type has assigned products. Update products first."
      );
      setDeleteTarget(null);
      return;
    }

    const { error } = await supabase
      .from("product_types")
      .update({ deleted_at: new Date().toISOString() })
      .eq("id", deleteTarget.id);

    if (error) {
      toast.error(lang === "bn" ? "ডিলিট করা যায়নি" : "Failed to delete");
    } else {
      toast.success(
        lang === "bn" ? "Product Type মুছে ফেলা হয়েছে" : "Product type deleted"
      );
      setTypes((prev) => prev.filter((t) => t.id !== deleteTarget.id));
    }
    setDeleteTarget(null);
  };

  return (
    <PageLayout>
      <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="text-xl font-bold text-foreground">
            {lang === "bn" ? "পণ্যের ধরন" : "Product Types"}
          </h1>
          <p className="text-sm text-muted-foreground">
            {lang === "bn"
              ? "সকল প্রোডাক্ট টাইপ ম্যানেজ করুন"
              : "Manage all product types"}{" "}
            — {types.length}{" "}
            {lang === "bn" ? "টি ধরন" : "types"}
          </p>
        </div>
        <button
          onClick={openAddModal}
          className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2.5 text-sm font-medium text-primary-foreground transition hover:bg-primary/90"
        >
          <Plus className="h-4 w-4" />
          {lang === "bn" ? "নতুন ধরন যোগ করুন" : "Add Product Type"}
        </button>
      </div>

      {/* Filters */}
      <div className="mb-4 flex flex-wrap items-center gap-3">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <input
            type="text"
            placeholder={
              lang === "bn" ? "ধরন খুঁজুন..." : "Search product types..."
            }
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full rounded-lg border border-input bg-card py-2 pl-10 pr-4 text-sm outline-none focus:ring-2 focus:ring-ring"
          />
        </div>
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="rounded-lg border border-input bg-card px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
        >
          <option value="all">
            {lang === "bn" ? "সব স্ট্যাটাস" : "All Status"}
          </option>
          <option value="active">
            {lang === "bn" ? "সক্রিয়" : "Active"}
          </option>
          <option value="inactive">
            {lang === "bn" ? "নিষ্ক্রিয়" : "Inactive"}
          </option>
        </select>
      </div>

      {/* Table */}
      {loading ? (
        <div className="flex h-40 items-center justify-center text-muted-foreground">
          {lang === "bn" ? "লোড হচ্ছে..." : "Loading..."}
        </div>
      ) : (
        <div className="rounded-xl border border-border bg-card overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border text-left text-xs text-muted-foreground">
                <th className="px-4 py-3 font-medium">
                  {lang === "bn" ? "আইকন" : "Icon"}
                </th>
                <th className="px-4 py-3 font-medium">
                  {lang === "bn" ? "টাইপ নাম" : "Type Name"}
                </th>
                <th className="px-4 py-3 font-medium">
                  {lang === "bn" ? "স্ট্যাটাস" : "Status"}
                </th>
                <th className="px-4 py-3 font-medium">
                  {lang === "bn" ? "মোট পণ্য" : "Total Products"}
                </th>
                <th className="px-4 py-3 font-medium">
                  {lang === "bn" ? "তারিখ" : "Created"}
                </th>
                <th className="px-4 py-3 font-medium">
                  {lang === "bn" ? "অ্যাকশন" : "Action"}
                </th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((t) => (
                <tr
                  key={t.id}
                  className="border-b border-border last:border-0 hover:bg-muted/30"
                >
                  <td className="px-4 py-3">
                    <div className={`flex h-9 w-9 items-center justify-center rounded-lg text-lg ${
                      t.name.toLowerCase() === "electric"
                        ? "bg-yellow-100 dark:bg-yellow-900/30"
                        : t.name.toLowerCase() === "hardware"
                          ? "bg-blue-100 dark:bg-blue-900/30"
                          : "bg-muted"
                    }`}>
                      {t.icon || "📦"}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <span
                        className={`inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-semibold ${
                          t.name.toLowerCase() === "electric"
                            ? "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400"
                            : t.name.toLowerCase() === "hardware"
                              ? "bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400"
                              : "bg-muted text-muted-foreground"
                        }`}
                      >
                        {t.icon} {lang === "bn" ? t.name_bn || t.name : t.name}
                      </span>
                    </div>
                    <p className="mt-0.5 text-xs text-muted-foreground">
                      {lang === "bn" ? t.name : t.name_bn}
                    </p>
                  </td>
                  <td className="px-4 py-3">
                    <span
                      className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
                        t.status === "active"
                          ? "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400"
                          : "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400"
                      }`}
                    >
                      {t.status === "active"
                        ? lang === "bn"
                          ? "সক্রিয়"
                          : "Active"
                        : lang === "bn"
                          ? "নিষ্ক্রিয়"
                          : "Inactive"}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <span className="inline-flex items-center gap-1 text-sm">
                      <Package className="h-3.5 w-3.5 text-muted-foreground" />
                      {t.product_count || 0}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-xs text-muted-foreground">
                    {new Date(t.created_at).toLocaleDateString(
                      lang === "bn" ? "bn-BD" : "en-US"
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex gap-1">
                      <button
                        onClick={() => openEditModal(t)}
                        className="rounded p-1.5 text-muted-foreground hover:bg-secondary hover:text-foreground"
                      >
                        <Edit className="h-3.5 w-3.5" />
                      </button>
                      <button
                        onClick={() => setDeleteTarget(t)}
                        className="rounded p-1.5 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {filtered.length === 0 && (
            <div className="flex h-32 items-center justify-center text-muted-foreground">
              <Tag className="mr-2 h-4 w-4" />
              {lang === "bn"
                ? "কোনো Product Type পাওয়া যায়নি"
                : "No product types found"}
            </div>
          )}
        </div>
      )}

      {/* Add/Edit Modal */}
      {modalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="w-full max-w-md rounded-xl bg-card border border-border p-6 shadow-xl">
            <h2 className="text-lg font-bold text-foreground mb-4">
              {editingType
                ? lang === "bn"
                  ? "Product Type সম্পাদনা"
                  : "Edit Product Type"
                : lang === "bn"
                  ? "নতুন Product Type যোগ করুন"
                  : "Add Product Type"}
            </h2>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  {lang === "bn" ? "টাইপ নাম (English) *" : "Type Name (English) *"}
                </label>
                <input
                  type="text"
                  value={formName}
                  onChange={(e) => setFormName(e.target.value)}
                  placeholder="e.g. Electric"
                  className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  {lang === "bn" ? "টাইপ নাম (বাংলা)" : "Type Name (Bengali)"}
                </label>
                <input
                  type="text"
                  value={formNameBn}
                  onChange={(e) => setFormNameBn(e.target.value)}
                  placeholder="যেমন: ইলেকট্রিক"
                  className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  {lang === "bn" ? "আইকন (Emoji)" : "Icon (Emoji)"}
                </label>
                <input
                  type="text"
                  value={formIcon}
                  onChange={(e) => setFormIcon(e.target.value)}
                  placeholder="⚡"
                  className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  {lang === "bn" ? "স্ট্যাটাস" : "Status"}
                </label>
                <select
                  value={formStatus}
                  onChange={(e) => setFormStatus(e.target.value)}
                  className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
                >
                  <option value="active">
                    {lang === "bn" ? "সক্রিয়" : "Active"}
                  </option>
                  <option value="inactive">
                    {lang === "bn" ? "নিষ্ক্রিয়" : "Inactive"}
                  </option>
                </select>
              </div>
            </div>

            <div className="mt-6 flex justify-end gap-3">
              <button
                onClick={() => setModalOpen(false)}
                className="rounded-lg border border-input bg-background px-4 py-2 text-sm font-medium text-foreground hover:bg-muted"
              >
                {lang === "bn" ? "বাতিল" : "Cancel"}
              </button>
              <button
                onClick={handleSave}
                disabled={saving}
                className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
              >
                {saving
                  ? lang === "bn"
                    ? "সেভ হচ্ছে..."
                    : "Saving..."
                  : lang === "bn"
                    ? "সেভ করুন"
                    : "Save"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Delete Confirmation */}
      {deleteTarget && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="w-full max-w-sm rounded-xl bg-card border border-border p-6 shadow-xl">
            <h2 className="text-lg font-bold text-foreground mb-2">
              {lang === "bn" ? "ডিলিট নিশ্চিত করুন" : "Confirm Delete"}
            </h2>
            <p className="text-sm text-muted-foreground mb-1">
              {lang === "bn"
                ? `"${deleteTarget.name_bn || deleteTarget.name}" মুছে ফেলতে চান?`
                : `Delete "${deleteTarget.name}"?`}
            </p>
            {(deleteTarget.product_count || 0) > 0 && (
              <p className="text-sm text-destructive mt-2">
                ⚠️{" "}
                {lang === "bn"
                  ? "এই Product Type এর সাথে Product যুক্ত আছে, আগে Product update করুন"
                  : "This type has assigned products. Update products first."}
              </p>
            )}
            <div className="mt-5 flex justify-end gap-3">
              <button
                onClick={() => setDeleteTarget(null)}
                className="rounded-lg border border-input bg-background px-4 py-2 text-sm font-medium text-foreground hover:bg-muted"
              >
                {lang === "bn" ? "বাতিল" : "Cancel"}
              </button>
              <button
                onClick={handleDelete}
                className="rounded-lg bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground hover:bg-destructive/90"
              >
                {lang === "bn" ? "ডিলিট করুন" : "Delete"}
              </button>
            </div>
          </div>
        </div>
      )}
    </PageLayout>
  );
}
