import { Show, createSignal, createMemo } from "solid-js";
import { Input } from "../../components/ui/input";
import { getInitials } from "../../components/dashboard/types";
import { UsersIcon, XIcon } from "../../components/dashboard/icons";
import { DashboardLayout, useDashboardData } from "./layout";

function CustomersPage() {
  const data = useDashboardData();
  const [searchQuery, setSearchQuery] = createSignal("");
  const [selectedCustomer, setSelectedCustomer] = createSignal<any>(null);
  const [showCustomerDetail, setShowCustomerDetail] = createSignal(false);
  const [pinnedCustomerIds, setPinnedCustomerIds] = createSignal<Set<string>>(new Set());

  const demoCustomers = [
    { id: "1", name: "Martina Novakova", email: "martina@example.com", phone: "+420 123 456 789", bookingsCount: 5, lastBookingAt: new Date(Date.now() - 86400000).toISOString(), status: "active", notes: "Alergie na silne vune" },
    { id: "2", name: "David Svoboda", email: "david@example.com", phone: "+420 987 654 321", bookingsCount: 3, lastBookingAt: new Date(Date.now() - 172800000).toISOString(), status: "active", notes: "" },
    { id: "3", name: "Jana KovarovA", email: "jana@example.com", phone: "+420 555 666 777", bookingsCount: 8, lastBookingAt: new Date(Date.now() - 259200000).toISOString(), status: "vip", notes: "Uprednostnuje ranni terminy" },
    { id: "4", name: "Alice Johnson", email: "alice@example.com", phone: "+420 111 222 333", bookingsCount: 1, lastBookingAt: new Date(Date.now() - 604800000).toISOString(), status: "inactive", notes: "" },
    { id: "5", name: "Bob Smith", email: "bob@example.com", phone: "+420 444 555 666", bookingsCount: 12, lastBookingAt: new Date(Date.now() - 432000000).toISOString(), status: "vip", notes: "Loyal customer" },
  ];

  const resolvedCustomers = () => demoCustomers;
  const resolvedBookings = () => data.normalizedAllBookings();

  const filteredCustomers = createMemo(() => {
    let result = resolvedCustomers();
    if (searchQuery().trim()) {
      const q = searchQuery().toLowerCase();
      result = result.filter((c: any) => c.name?.toLowerCase().includes(q) || c.email?.toLowerCase().includes(q) || c.phone?.toLowerCase().includes(q));
    }
    return result.sort((a: any, b: any) => {
      const aPinned = pinnedCustomerIds().has(a.id) ? 1 : 0;
      const bPinned = pinnedCustomerIds().has(b.id) ? 1 : 0;
      if (aPinned !== bPinned) return bPinned - aPinned;
      return new Date(b.lastBookingAt || 0).getTime() - new Date(a.lastBookingAt || 0).getTime();
    });
  });

  const getCustomerBookings = (email: string) => {
    return resolvedBookings().filter((b: any) => b.customerEmail?.toLowerCase() === email?.toLowerCase()).sort((a: any, b: any) => new Date(b.startsAt).getTime() - new Date(a.startsAt).getTime());
  };

  const statusBadge = (status: string) => {
    switch (status) {
      case "active": return <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-accent/10 text-accent">{data.i18n.t("dashboard.filter.all")}</span>;
      case "vip": return <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-ink/10 text-ink">VIP</span>;
      default: return <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-canvas-subtle text-ink-subtle">{data.i18n.t("dashboard.customer.status")}</span>;
    }
  };

  return (
    <div class="space-y-6">
      <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 class="text-2xl sm:text-3xl font-bold text-ink font-display">{data.i18n.t("dashboard.customers")}</h1>
          <p class="text-ink-muted mt-1">{filteredCustomers().length} {data.i18n.locale() === "cs" ? "zakazniku" : "customers"}</p>
        </div>
      </div>
      <div class="surface-card p-4">
        <Input type="text" placeholder={data.i18n.t("dashboard.search.customers")} value={searchQuery()} onInput={(e) => setSearchQuery(e.currentTarget.value)} />
      </div>
      <div class="surface-card overflow-hidden">
        <Show when={filteredCustomers().length > 0} fallback={
          <div class="p-12 text-center">
            <div class="w-16 h-16 rounded-full bg-canvas-subtle flex items-center justify-center mx-auto mb-4"><UsersIcon /></div>
            <p class="text-ink-muted font-medium">{data.i18n.t("dashboard.empty.title")}</p>
            <p class="text-sm text-ink-subtle mt-1">{data.i18n.t("dashboard.empty.customersDesc")}</p>
          </div>
        }>
          <div class="divide-y divide-border/60">
            {filteredCustomers().map((customer: any) => {
              const isPinned = () => pinnedCustomerIds().has(customer.id);
              const togglePin = (e: Event) => {
                e.stopPropagation();
                setPinnedCustomerIds((prev) => {
                  const next = new Set(prev);
                  if (next.has(customer.id)) next.delete(customer.id);
                  else next.add(customer.id);
                  return next;
                });
              };
              return (
                <button onClick={() => { setSelectedCustomer(customer); setShowCustomerDetail(true); }} class={`w-full text-left flex items-center gap-4 p-4 hover:bg-canvas-subtle/30 transition-colors ${isPinned() ? "bg-accent-soft/40" : ""}`}>
                  <div class="w-10 h-10 rounded-full bg-accent-subtle flex items-center justify-center text-sm font-bold text-accent shrink-0">{getInitials(customer.name)}</div>
                  <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-2">
                      <p class="font-medium text-ink">{customer.name}</p>
                      {statusBadge(customer.status)}
                      {isPinned() && (
                        <span class="w-1.5 h-1.5 rounded-full bg-accent" />
                      )}
                    </div>
                    <p class="text-sm text-ink-muted">{customer.email}</p>
                  </div>
                  <div class="flex items-center gap-3 shrink-0">
                    <button
                      type="button"
                      onClick={togglePin}
                      class={`flex h-6 w-6 items-center justify-center rounded-full transition-all duration-200 ${
                        isPinned()
                          ? "bg-accent text-canvas hover:bg-accent-hover"
                          : "bg-canvas-subtle border border-border text-ink-subtle hover:border-accent/40 hover:text-accent"
                      }`}
                      aria-label={isPinned() ? "Unpin" : "Pin"}
                    >
                      <svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor">
                        <circle cx="5" cy="5" r="4" class={isPinned() ? "" : "opacity-0"} />
                        <circle cx="5" cy="5" r="3.5" fill="none" stroke="currentColor" stroke-width="1" class={isPinned() ? "opacity-0" : ""} />
                      </svg>
                    </button>
                    <div class="text-right hidden sm:block">
                      <p class="text-sm font-medium text-ink">{customer.bookingsCount}</p>
                      <p class="text-xs text-ink-muted">{data.i18n.t("dashboard.customer.totalBookings")}</p>
                    </div>
                  </div>
                </button>
              );
            })}
          </div>
        </Show>
      </div>

      {/* Customer Detail Modal */}
      <Show when={showCustomerDetail() && selectedCustomer()}>
        <div class="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div class="absolute inset-0 bg-ink/50 backdrop-blur-sm" onClick={() => setShowCustomerDetail(false)} />
          <div class="relative bg-canvas rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto animate-scale-in">
            <div class="p-6 border-b border-border flex items-center justify-between">
              <h3 class="text-xl font-bold text-ink">{data.i18n.t("dashboard.customerDetails")}</h3>
              <button onClick={() => setShowCustomerDetail(false)} class="p-2 hover:bg-canvas-subtle rounded-lg transition-colors"><XIcon /></button>
            </div>
            <div class="p-6 space-y-5">
              <div class="flex items-center gap-4 p-4 bg-canvas-subtle rounded-xl">
                <div class="w-14 h-14 rounded-full bg-accent-subtle flex items-center justify-center text-lg font-bold text-accent">{getInitials(selectedCustomer().name)}</div>
                <div>
                  <p class="font-semibold text-ink text-lg">{selectedCustomer().name}</p>
                  <p class="text-ink-muted">{selectedCustomer().email}</p>
                </div>
              </div>
              <div class="grid grid-cols-2 gap-4">
                <div class="p-4 bg-canvas-subtle rounded-xl"><p class="text-xs text-ink-muted uppercase tracking-wider mb-1">{data.i18n.t("dashboard.customer.phone")}</p><p class="font-medium text-ink">{selectedCustomer().phone}</p></div>
                <div class="p-4 bg-canvas-subtle rounded-xl"><p class="text-xs text-ink-muted uppercase tracking-wider mb-1">{data.i18n.t("dashboard.customer.totalBookings")}</p><p class="font-medium text-ink">{selectedCustomer().bookingsCount}</p></div>
              </div>
              <Show when={selectedCustomer().notes}>
                <div class="p-4 bg-canvas-subtle rounded-xl"><p class="text-xs text-ink-muted uppercase tracking-wider mb-1">{data.i18n.t("dashboard.customer.notes")}</p><p class="text-ink text-sm">{selectedCustomer().notes}</p></div>
              </Show>
              <div>
                <p class="text-sm font-semibold text-ink mb-3">{data.i18n.t("dashboard.customer.bookings")}</p>
                <div class="space-y-2">
                  {getCustomerBookings(selectedCustomer().email).slice(0, 5).map((b: any) => (
                    <div class="flex items-center gap-3 p-3 rounded-xl border border-border/60">
                      <div class="flex-1 min-w-0">
                        <p class="text-sm font-medium text-ink">{b.service}</p>
                        <p class="text-xs text-ink-muted">{new Date(b.startsAt).toLocaleDateString()}</p>
                      </div>
                      <span class={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${b.status === "confirmed" ? "bg-accent/10 text-accent" : "bg-canvas-muted text-ink-muted"}`}>{data.i18n.t(`dashboard.${b.status}`)}</span>
                    </div>
                  ))}
                  <Show when={getCustomerBookings(selectedCustomer().email).length === 0}>
                    <p class="text-sm text-ink-muted">{data.i18n.t("dashboard.customer.noBookings")}</p>
                  </Show>
                </div>
              </div>
            </div>
          </div>
        </div>
      </Show>
    </div>
  );
}

export default function CustomersRoute() {
  return (
    <DashboardLayout>
      <CustomersPage />
    </DashboardLayout>
  );
}
