/**
 * Customers Panel Component
 * Full customer management with add, view, edit, delete, and search
 */

"use client";

import { useState, useMemo, useEffect, useCallback } from "react";
import type { Lang } from "@/lib/config";
import { dashboardEn } from "@/lib/config/translations/modules/dashboard.en";
import { dashboardAr } from "@/lib/config/translations/modules/dashboard.ar";
import {
  Plus,
  Search,
  X,
  User,
  Phone,
  Mail,
  FileText,
  Calendar,
  MessageSquare,
  Edit3,
  Trash2,
  ChevronRight,
  Users,
  UserPlus,
  Clock,
  Loader2,
} from "lucide-react";

// Customer type from database
interface DBCustomer {
  id: string;
  name: string;
  phone: string;
  email: string | null;
  notes: string | null;
  createdAt: string;
  updatedAt: string;
}

// Customer type for frontend state (enriched with booking data)
interface Customer {
  id: string;
  name: string;
  phone: string;
  email: string;
  notes: string;
  createdAt: Date;
  bookings: any[];
  totalSpent: number;
  lastVisit: Date | null;
  isFromDB: boolean; // Flag to track if customer is from database
}

interface CustomersPanelProps {
  lang: Lang;
  bookings: any[];
}

// Helper to get CSRF token from cookies
function getCSRFToken(): string | null {
  if (typeof document === "undefined") return null;
  const match = document.cookie.match(/csrf-token=([^;]+)/);
  return match ? match[1] : null;
}

export default function CustomersPanel({
  lang,
  bookings,
}: CustomersPanelProps) {
  const isAr = lang === "ar";
  const dt = isAr ? dashboardAr : dashboardEn;

  // State
  const [searchQuery, setSearchQuery] = useState("");
  const [showAddModal, setShowAddModal] = useState(false);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(
    null,
  );
  const [isEditing, setIsEditing] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [apiError, setApiError] = useState<string | null>(null);

  // Form state
  const [formData, setFormData] = useState({
    name: "",
    phone: "",
    email: "",
    notes: "",
  });
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});

  // Database customers state
  const [dbCustomers, setDbCustomers] = useState<DBCustomer[]>([]);

  // Fetch customers from API
  const fetchCustomers = useCallback(async () => {
    try {
      setIsLoading(true);
      setApiError(null);
      const response = await fetch("/api/user/customers");
      const data = await response.json();

      if (data.success) {
        setDbCustomers(data.customers || []);
      } else {
        setApiError(data.error || "Failed to load customers");
      }
    } catch (error) {
      console.error("Failed to fetch customers:", error);
      setApiError("Failed to load customers");
    } finally {
      setIsLoading(false);
    }
  }, []);

  // Load customers on mount
  useEffect(() => {
    fetchCustomers();
  }, [fetchCustomers]);

  // Aggregate customers from bookings and merge with database customers
  const allCustomers = useMemo(() => {
    const customerMap = new Map<string, Customer>();

    // Add customers from bookings first
    bookings.forEach((booking) => {
      const key = booking.customerPhone;
      if (!customerMap.has(key)) {
        customerMap.set(key, {
          id: `booking-${key}`,
          phone: booking.customerPhone,
          name: booking.customerName,
          email: booking.customerEmail || "",
          notes: "",
          createdAt: new Date(booking.createdAt || booking.appointmentDate),
          bookings: [],
          totalSpent: 0,
          lastVisit: booking.appointmentDate
            ? new Date(booking.appointmentDate)
            : null,
          isFromDB: false,
        });
      }

      const customer = customerMap.get(key)!;
      customer.bookings.push(booking);
      if (booking.status === "completed" || booking.depositPaid) {
        customer.totalSpent += booking.depositPaid
          ? booking.depositAmount || 0
          : 0;
      }
      // Update last visit if this booking is more recent
      if (booking.appointmentDate) {
        const bookingDate = new Date(booking.appointmentDate);
        if (!customer.lastVisit || bookingDate > customer.lastVisit) {
          customer.lastVisit = bookingDate;
        }
      }
    });

    // Add database customers (overwrite if same phone, preserving booking data)
    dbCustomers.forEach((dbCustomer) => {
      const existing = customerMap.get(dbCustomer.phone);
      if (existing) {
        // Merge database data with booking data
        customerMap.set(dbCustomer.phone, {
          ...existing,
          id: dbCustomer.id,
          name: dbCustomer.name,
          email: dbCustomer.email || "",
          notes: dbCustomer.notes || "",
          createdAt: new Date(dbCustomer.createdAt),
          isFromDB: true,
        });
      } else {
        customerMap.set(dbCustomer.phone, {
          id: dbCustomer.id,
          name: dbCustomer.name,
          phone: dbCustomer.phone,
          email: dbCustomer.email || "",
          notes: dbCustomer.notes || "",
          createdAt: new Date(dbCustomer.createdAt),
          bookings: [],
          totalSpent: 0,
          lastVisit: null,
          isFromDB: true,
        });
      }
    });

    return Array.from(customerMap.values()).sort(
      (a, b) => (b.lastVisit?.getTime() || 0) - (a.lastVisit?.getTime() || 0),
    );
  }, [bookings, dbCustomers]);

  // Filter customers by search
  const filteredCustomers = useMemo(() => {
    if (!searchQuery.trim()) return allCustomers;
    const query = searchQuery.toLowerCase();
    return allCustomers.filter(
      (c) =>
        c.name?.toLowerCase().includes(query) ||
        c.phone?.includes(query) ||
        c.email?.toLowerCase().includes(query),
    );
  }, [allCustomers, searchQuery]);

  // Stats
  const totalCustomers = allCustomers.length;
  const returningCustomers = allCustomers.filter(
    (c) => c.bookings.length > 1,
  ).length;
  const avgBookings =
    totalCustomers > 0
      ? (
          allCustomers.reduce((sum, c) => sum + c.bookings.length, 0) /
          totalCustomers
        ).toFixed(1)
      : "0";

  // Form validation
  const validateForm = () => {
    const errors: Record<string, string> = {};

    if (!formData.name.trim()) {
      errors.name = dt.requiredField;
    }

    if (!formData.phone.trim()) {
      errors.phone = dt.requiredField;
    } else if (!/^[\d\s+()-]+$/.test(formData.phone)) {
      errors.phone = dt.invalidPhone;
    }

    if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      errors.email = dt.invalidEmail;
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // Handlers
  const handleOpenAddModal = () => {
    setFormData({ name: "", phone: "", email: "", notes: "" });
    setFormErrors({});
    setIsEditing(false);
    setShowAddModal(true);
  };

  const handleOpenEditModal = (customer: Customer) => {
    setFormData({
      name: customer.name,
      phone: customer.phone,
      email: customer.email,
      notes: customer.notes,
    });
    setFormErrors({});
    setSelectedCustomer(customer);
    setIsEditing(true);
    setShowAddModal(true);
  };

  const handleOpenDetailModal = (customer: Customer) => {
    setSelectedCustomer(customer);
    setShowDetailModal(true);
  };

  const handleOpenDeleteModal = (customer: Customer) => {
    setSelectedCustomer(customer);
    setShowDeleteModal(true);
  };

  const handleSaveCustomer = async () => {
    if (!validateForm()) return;

    setIsSaving(true);
    setApiError(null);

    try {
      const csrfToken = getCSRFToken();
      const headers: HeadersInit = {
        "Content-Type": "application/json",
      };
      if (csrfToken) {
        headers["x-csrf-token"] = csrfToken;
      }

      if (isEditing && selectedCustomer && selectedCustomer.isFromDB) {
        // Update existing customer in database
        const response = await fetch(
          `/api/user/customers/${selectedCustomer.id}`,
          {
            method: "PUT",
            headers,
            body: JSON.stringify({
              name: formData.name,
              phone: formData.phone,
              email: formData.email || null,
              notes: formData.notes || null,
            }),
          },
        );

        const data = await response.json();

        if (!data.success) {
          setApiError(data.error || "Failed to update customer");
          return;
        }
      } else {
        // Create new customer in database
        const response = await fetch("/api/user/customers", {
          method: "POST",
          headers,
          body: JSON.stringify({
            name: formData.name,
            phone: formData.phone,
            email: formData.email || null,
            notes: formData.notes || null,
          }),
        });

        const data = await response.json();

        if (!data.success) {
          setApiError(data.error || "Failed to create customer");
          return;
        }
      }

      // Refresh the customer list
      await fetchCustomers();

      setShowAddModal(false);
      setFormData({ name: "", phone: "", email: "", notes: "" });
      setSelectedCustomer(null);
    } catch (error) {
      console.error("Failed to save customer:", error);
      setApiError("Failed to save customer");
    } finally {
      setIsSaving(false);
    }
  };

  const handleDeleteCustomer = async () => {
    if (!selectedCustomer || !selectedCustomer.isFromDB) {
      setShowDeleteModal(false);
      setSelectedCustomer(null);
      return;
    }

    setIsSaving(true);
    setApiError(null);

    try {
      const csrfToken = getCSRFToken();
      const headers: HeadersInit = {
        "Content-Type": "application/json",
      };
      if (csrfToken) {
        headers["x-csrf-token"] = csrfToken;
      }

      const response = await fetch(
        `/api/user/customers/${selectedCustomer.id}`,
        {
          method: "DELETE",
          headers,
        },
      );

      const data = await response.json();

      if (!data.success) {
        setApiError(data.error || "Failed to delete customer");
        return;
      }

      // Refresh the customer list
      await fetchCustomers();

      setShowDeleteModal(false);
      setSelectedCustomer(null);
    } catch (error) {
      console.error("Failed to delete customer:", error);
      setApiError("Failed to delete customer");
    } finally {
      setIsSaving(false);
    }
  };

  const formatDate = (date: Date | null) => {
    if (!date) return "-";
    return date.toLocaleDateString(isAr ? "ar-SA" : "en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    });
  };

  return (
    <div className="space-y-6 animate-fadeIn">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-slate-900">{dt.customers}</h2>
          <p className="text-slate-600 mt-1">{dt.customersDesc}</p>
        </div>
        <button
          onClick={handleOpenAddModal}
          className="inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 px-5 py-3 text-sm font-semibold text-white shadow-lg shadow-brand-green/25 hover:shadow-brand-green/40 hover:-translate-y-0.5 transition-all"
        >
          <UserPlus className="w-4 h-4" />
          <span>{dt.addCustomer}</span>
        </button>
      </div>

      {/* Stats Cards */}
      <div className="grid gap-4 sm:grid-cols-3">
        <div className="rounded-2xl bg-gradient-to-br from-emerald-50 to-teal-50 border border-emerald-200/50 p-5">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-emerald-500 to-teal-600 shadow-lg">
              <Users className="w-5 h-5 text-white" />
            </div>
            <div>
              <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider">
                {dt.totalCustomers}
              </p>
              <p className="text-2xl font-bold text-emerald-700">
                {totalCustomers}
              </p>
            </div>
          </div>
        </div>
        <div className="rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-200/50 p-5">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-blue-500 to-indigo-600 shadow-lg">
              <UserPlus className="w-5 h-5 text-white" />
            </div>
            <div>
              <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider">
                {dt.returningCustomers}
              </p>
              <p className="text-2xl font-bold text-blue-700">
                {returningCustomers}
              </p>
            </div>
          </div>
        </div>
        <div className="rounded-2xl bg-gradient-to-br from-violet-50 to-purple-50 border border-violet-200/50 p-5">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-violet-500 to-purple-600 shadow-lg">
              <Calendar className="w-5 h-5 text-white" />
            </div>
            <div>
              <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider">
                {dt.avgBookingsPerCustomer}
              </p>
              <p className="text-2xl font-bold text-violet-700">
                {avgBookings}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Search */}
      <div className="relative">
        <input
          type="text"
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          placeholder={dt.searchCustomers}
          className="w-full h-12 pl-12 pr-4 rounded-xl border border-slate-200 bg-white text-sm placeholder-slate-400 transition-all focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 focus:outline-none"
        />
        <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
        {searchQuery && (
          <button
            onClick={() => setSearchQuery("")}
            className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400 hover:text-slate-600"
          >
            <X className="w-5 h-5" />
          </button>
        )}
      </div>

      {/* API Error Display */}
      {apiError && (
        <div className="rounded-xl bg-red-50 border border-red-200 p-4 mb-4">
          <p className="text-sm text-red-700">{apiError}</p>
        </div>
      )}

      {/* Customer List */}
      <div className="rounded-2xl bg-white border border-slate-200/80 shadow-sm overflow-hidden">
        {isLoading ? (
          <div className="flex flex-col items-center justify-center p-16 text-center">
            <Loader2 className="w-8 h-8 text-brand-green animate-spin mb-4" />
            <p className="text-sm text-slate-500">
              {isAr ? "جاري التحميل..." : "Loading customers..."}
            </p>
          </div>
        ) : filteredCustomers.length === 0 ? (
          <div className="flex flex-col items-center justify-center p-16 text-center">
            <div className="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center mb-4">
              <Users className="w-8 h-8 text-slate-400" />
            </div>
            <p className="text-lg font-semibold text-slate-600">
              {dt.noCustomersYet}
            </p>
            <p className="mt-2 text-sm text-slate-400 max-w-sm">
              {dt.noCustomersYetDesc}
            </p>
            <button
              onClick={handleOpenAddModal}
              className="mt-6 inline-flex items-center gap-2 rounded-xl bg-brand-green px-5 py-2.5 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors"
            >
              <Plus className="w-4 h-4" />
              {dt.addCustomer}
            </button>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-slate-50 border-b border-slate-200">
                <tr>
                  <th className="px-6 py-4 text-left font-semibold text-slate-700">
                    {dt.customerName}
                  </th>
                  <th className="px-6 py-4 text-left font-semibold text-slate-700">
                    {dt.phone}
                  </th>
                  <th className="px-6 py-4 text-left font-semibold text-slate-700 hidden md:table-cell">
                    {dt.email}
                  </th>
                  <th className="px-6 py-4 text-center font-semibold text-slate-700">
                    {dt.totalBookings}
                  </th>
                  <th className="px-6 py-4 text-left font-semibold text-slate-700 hidden lg:table-cell">
                    {dt.lastVisit}
                  </th>
                  <th className="px-6 py-4 text-right font-semibold text-slate-700">
                    {dt.lifetimeValue}
                  </th>
                  <th className="px-6 py-4 text-center font-semibold text-slate-700">
                    {dt.actions}
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {filteredCustomers.map((customer) => (
                  <tr
                    key={customer.id}
                    className="hover:bg-slate-50 transition-colors"
                  >
                    <td className="px-6 py-4">
                      <button
                        onClick={() => handleOpenDetailModal(customer)}
                        className="flex items-center gap-3 group"
                      >
                        <div className="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-brand-green/20 to-emerald-500/20 text-sm font-bold text-brand-green">
                          {customer.name?.charAt(0).toUpperCase() || "?"}
                        </div>
                        <span className="font-medium text-slate-900 group-hover:text-brand-green transition-colors">
                          {customer.name || "-"}
                        </span>
                      </button>
                    </td>
                    <td className="px-6 py-4">
                      <span className="text-slate-700 font-mono text-xs">
                        {customer.phone}
                      </span>
                    </td>
                    <td className="px-6 py-4 hidden md:table-cell">
                      <span className="text-slate-600">
                        {customer.email || "-"}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-center">
                      <span className="inline-flex h-7 min-w-[28px] items-center justify-center rounded-full bg-emerald-100 px-2 text-xs font-bold text-emerald-700">
                        {customer.bookings.length}
                      </span>
                    </td>
                    <td className="px-6 py-4 hidden lg:table-cell">
                      <span className="text-slate-600 text-xs">
                        {formatDate(customer.lastVisit)}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-right">
                      <span className="font-semibold text-slate-900">
                        QAR {customer.totalSpent.toFixed(2)}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center justify-center gap-1">
                        <button
                          onClick={() => handleOpenDetailModal(customer)}
                          className="p-2 rounded-lg text-slate-400 hover:text-brand-green hover:bg-brand-green/10 transition-colors"
                          title={dt.viewCustomerDetails}
                        >
                          <ChevronRight className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleOpenEditModal(customer)}
                          className="p-2 rounded-lg text-slate-400 hover:text-blue-600 hover:bg-blue-50 transition-colors"
                          title={dt.edit}
                        >
                          <Edit3 className="w-4 h-4" />
                        </button>
                        {customer.isFromDB && (
                          <button
                            onClick={() => handleOpenDeleteModal(customer)}
                            className="p-2 rounded-lg text-slate-400 hover:text-red-600 hover:bg-red-50 transition-colors"
                            title={dt.delete}
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Add/Edit Customer Modal - Premium Design */}
      {showAddModal && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center p-4"
          onClick={() => setShowAddModal(false)}
        >
          {/* Modal Container */}
          <div
            className="relative w-full max-w-lg transform transition-all duration-300 ease-out animate-fadeIn"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Modal Content */}
            <div className="relative bg-white rounded-2xl shadow-2xl overflow-hidden">
              {/* Header with gradient accent */}
              <div className="relative px-8 pt-8 pb-6">
                {/* Top accent bar */}
                <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-brand-green via-emerald-400 to-teal-500" />

                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-4">
                    {/* Icon container with gradient */}
                    <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-green to-emerald-600 shadow-lg shadow-brand-green/30">
                      <UserPlus className="w-7 h-7 text-white" />
                    </div>
                    <div>
                      <h3 className="text-2xl font-bold text-slate-900">
                        {isEditing ? dt.editCustomer : dt.addNewCustomer}
                      </h3>
                      <p className="text-sm text-slate-500 mt-1">
                        {isAr
                          ? "أدخل معلومات العميل أدناه"
                          : "Enter customer information below"}
                      </p>
                    </div>
                  </div>
                  <button
                    onClick={() => setShowAddModal(false)}
                    className="flex h-10 w-10 items-center justify-center rounded-xl text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-all duration-200"
                  >
                    <X className="w-5 h-5" />
                  </button>
                </div>
              </div>

              {/* Form Body */}
              <div className="px-8 pb-6 space-y-6">
                {/* Name & Phone in grid on larger screens */}
                <div className="grid gap-6 sm:grid-cols-2">
                  {/* Name Field */}
                  <div className="sm:col-span-2">
                    <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 mb-3">
                      <span className="flex h-6 w-6 items-center justify-center rounded-lg bg-slate-100">
                        <User className="w-3.5 h-3.5 text-slate-500" />
                      </span>
                      {dt.fullName}
                      <span className="text-red-500">*</span>
                    </label>
                    <div className="relative group">
                      <input
                        type="text"
                        value={formData.name}
                        onChange={(e) =>
                          setFormData({ ...formData, name: e.target.value })
                        }
                        placeholder={dt.fullNamePlaceholder}
                        className={`w-full h-14 px-5 rounded-xl border-2 ${
                          formErrors.name
                            ? "border-red-300 bg-red-50/50 focus:border-red-500 focus:ring-red-200"
                            : "border-slate-200 bg-slate-50/50 focus:border-brand-green focus:bg-white focus:ring-brand-green/20"
                        } text-base font-medium placeholder-slate-400 transition-all duration-200 focus:ring-4 focus:outline-none`}
                      />
                      {formErrors.name && (
                        <p className="mt-2 text-sm text-red-500 flex items-center gap-1">
                          <span className="w-1 h-1 rounded-full bg-red-500" />
                          {formErrors.name}
                        </p>
                      )}
                    </div>
                  </div>

                  {/* Phone Field */}
                  <div>
                    <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 mb-3">
                      <span className="flex h-6 w-6 items-center justify-center rounded-lg bg-emerald-100">
                        <Phone className="w-3.5 h-3.5 text-emerald-600" />
                      </span>
                      {dt.mobileNumber}
                      <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <input
                        type="tel"
                        value={formData.phone}
                        onChange={(e) =>
                          setFormData({ ...formData, phone: e.target.value })
                        }
                        placeholder={dt.mobileNumberPlaceholder}
                        className={`w-full h-14 px-5 rounded-xl border-2 ${
                          formErrors.phone
                            ? "border-red-300 bg-red-50/50 focus:border-red-500 focus:ring-red-200"
                            : "border-slate-200 bg-slate-50/50 focus:border-brand-green focus:bg-white focus:ring-brand-green/20"
                        } text-base font-medium placeholder-slate-400 transition-all duration-200 focus:ring-4 focus:outline-none font-mono`}
                        dir="ltr"
                      />
                      {formErrors.phone && (
                        <p className="mt-2 text-sm text-red-500 flex items-center gap-1">
                          <span className="w-1 h-1 rounded-full bg-red-500" />
                          {formErrors.phone}
                        </p>
                      )}
                    </div>
                  </div>

                  {/* Email Field */}
                  <div>
                    <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 mb-3">
                      <span className="flex h-6 w-6 items-center justify-center rounded-lg bg-blue-100">
                        <Mail className="w-3.5 h-3.5 text-blue-600" />
                      </span>
                      {dt.emailAddress}
                      <span className="text-xs font-normal text-slate-400 ml-1">
                        {isAr ? "(اختياري)" : "(optional)"}
                      </span>
                    </label>
                    <div className="relative">
                      <input
                        type="email"
                        value={formData.email}
                        onChange={(e) =>
                          setFormData({ ...formData, email: e.target.value })
                        }
                        placeholder={dt.emailPlaceholder}
                        className={`w-full h-14 px-5 rounded-xl border-2 ${
                          formErrors.email
                            ? "border-red-300 bg-red-50/50 focus:border-red-500 focus:ring-red-200"
                            : "border-slate-200 bg-slate-50/50 focus:border-brand-green focus:bg-white focus:ring-brand-green/20"
                        } text-base font-medium placeholder-slate-400 transition-all duration-200 focus:ring-4 focus:outline-none`}
                        dir="ltr"
                      />
                      {formErrors.email && (
                        <p className="mt-2 text-sm text-red-500 flex items-center gap-1">
                          <span className="w-1 h-1 rounded-full bg-red-500" />
                          {formErrors.email}
                        </p>
                      )}
                    </div>
                  </div>
                </div>

                {/* Notes Field - Full Width */}
                <div>
                  <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 mb-3">
                    <span className="flex h-6 w-6 items-center justify-center rounded-lg bg-violet-100">
                      <FileText className="w-3.5 h-3.5 text-violet-600" />
                    </span>
                    {dt.notes}
                    <span className="text-xs font-normal text-slate-400 ml-1">
                      {isAr ? "(اختياري)" : "(optional)"}
                    </span>
                  </label>
                  <textarea
                    value={formData.notes}
                    onChange={(e) =>
                      setFormData({ ...formData, notes: e.target.value })
                    }
                    placeholder={dt.notesPlaceholder}
                    rows={3}
                    className="w-full px-5 py-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 text-base font-medium placeholder-slate-400 transition-all duration-200 focus:border-brand-green focus:bg-white focus:ring-4 focus:ring-brand-green/20 focus:outline-none resize-none"
                  />
                </div>
              </div>

              {/* Footer with gradient background */}
              <div className="px-8 py-6 bg-gradient-to-r from-slate-50 via-slate-100/50 to-slate-50 border-t border-slate-200">
                <div className="flex items-center justify-end gap-4">
                  <button
                    onClick={() => setShowAddModal(false)}
                    className="px-6 py-3 rounded-xl border-2 border-slate-200 bg-white text-sm font-bold text-slate-600 hover:bg-slate-50 hover:border-slate-300 transition-all duration-200"
                  >
                    {dt.cancelAction}
                  </button>
                  <button
                    onClick={handleSaveCustomer}
                    disabled={isSaving}
                    className="px-8 py-3 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 text-sm font-bold text-white shadow-lg shadow-brand-green/30 hover:shadow-brand-green/50 hover:-translate-y-0.5 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:translate-y-0 inline-flex items-center gap-2"
                  >
                    {isSaving && <Loader2 className="w-4 h-4 animate-spin" />}
                    {isEditing ? dt.updateCustomer : dt.saveCustomer}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Customer Detail Modal - Premium Design */}
      {showDetailModal && selectedCustomer && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center p-4"
          onClick={() => setShowDetailModal(false)}
        >
          {/* Backdrop with solid overlay */}
          <div className="absolute inset-0 bg-slate-900/95 backdrop-blur-sm" />

          {/* Modal Container */}
          <div
            className="relative w-full max-w-xl transform transition-all duration-300 ease-out animate-fadeIn"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Decorative gradient ring */}
            <div className="absolute -inset-1 bg-gradient-to-r from-brand-green via-emerald-400 to-teal-500 rounded-3xl opacity-20 blur-lg" />

            {/* Modal Content */}
            <div className="relative bg-white rounded-2xl shadow-2xl max-h-[85vh] overflow-hidden flex flex-col">
              {/* Header with customer profile */}
              <div className="relative">
                {/* Gradient background */}
                <div className="absolute inset-0 bg-gradient-to-br from-brand-green via-emerald-500 to-teal-600" />
                {/* Subtle pattern overlay */}
                <div className="absolute inset-0 opacity-10 bg-[radial-gradient(circle_at_1px_1px,white_1px,transparent_0)] bg-[length:20px_20px]" />

                <div className="relative px-8 pt-8 pb-6">
                  <button
                    onClick={() => setShowDetailModal(false)}
                    className="absolute top-4 right-4 flex h-10 w-10 items-center justify-center rounded-xl bg-white/20 text-white hover:bg-white/30 transition-all duration-200"
                  >
                    <X className="w-5 h-5" />
                  </button>

                  <div className="flex items-center gap-5">
                    <div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-white/20 backdrop-blur-sm text-3xl font-bold text-white shadow-lg ring-4 ring-white/30">
                      {selectedCustomer.name?.charAt(0).toUpperCase() || "?"}
                    </div>
                    <div>
                      <h3 className="text-2xl font-bold text-white">
                        {selectedCustomer.name}
                      </h3>
                      <p className="text-emerald-100 flex items-center gap-2 mt-2">
                        <Clock className="w-4 h-4" />
                        {dt.customerSince}{" "}
                        {formatDate(selectedCustomer.createdAt)}
                      </p>
                    </div>
                  </div>

                  {/* Quick Stats in header */}
                  <div className="grid grid-cols-2 gap-4 mt-6">
                    <div className="rounded-xl bg-white/15 backdrop-blur-sm px-4 py-3">
                      <p className="text-xs font-medium text-emerald-100">
                        {dt.totalBookings}
                      </p>
                      <p className="text-2xl font-bold text-white">
                        {selectedCustomer.bookings.length}
                      </p>
                    </div>
                    <div className="rounded-xl bg-white/15 backdrop-blur-sm px-4 py-3">
                      <p className="text-xs font-medium text-emerald-100">
                        {dt.lifetimeValue}
                      </p>
                      <p className="text-2xl font-bold text-white">
                        QAR {selectedCustomer.totalSpent.toFixed(0)}
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              {/* Body */}
              <div className="p-8 overflow-y-auto flex-1">
                {/* Contact Info */}
                <div className="mb-8">
                  <h5 className="flex items-center gap-2 text-sm font-bold text-slate-700 mb-4">
                    <span className="flex h-6 w-6 items-center justify-center rounded-lg bg-slate-100">
                      <User className="w-3.5 h-3.5 text-slate-500" />
                    </span>
                    {dt.contactInfo}
                  </h5>
                  <div className="space-y-3">
                    <div className="flex items-center gap-4 p-4 rounded-xl bg-gradient-to-r from-emerald-50 to-teal-50 border border-emerald-200/50">
                      <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-emerald-100">
                        <Phone className="w-5 h-5 text-emerald-600" />
                      </div>
                      <div>
                        <p className="text-xs font-medium text-slate-500">
                          {dt.phone}
                        </p>
                        <p className="text-base font-semibold text-slate-900 font-mono">
                          {selectedCustomer.phone}
                        </p>
                      </div>
                    </div>
                    {selectedCustomer.email && (
                      <div className="flex items-center gap-4 p-4 rounded-xl bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200/50">
                        <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-100">
                          <Mail className="w-5 h-5 text-blue-600" />
                        </div>
                        <div>
                          <p className="text-xs font-medium text-slate-500">
                            {dt.email}
                          </p>
                          <p className="text-base font-semibold text-slate-900">
                            {selectedCustomer.email}
                          </p>
                        </div>
                      </div>
                    )}
                    {selectedCustomer.notes && (
                      <div className="flex items-start gap-4 p-4 rounded-xl bg-gradient-to-r from-violet-50 to-purple-50 border border-violet-200/50">
                        <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-violet-100">
                          <FileText className="w-5 h-5 text-violet-600" />
                        </div>
                        <div>
                          <p className="text-xs font-medium text-slate-500">
                            {dt.notes}
                          </p>
                          <p className="text-sm text-slate-700 mt-1">
                            {selectedCustomer.notes}
                          </p>
                        </div>
                      </div>
                    )}
                  </div>
                </div>

                {/* Appointment History */}
                <div>
                  <h5 className="flex items-center gap-2 text-sm font-bold text-slate-700 mb-4">
                    <span className="flex h-6 w-6 items-center justify-center rounded-lg bg-slate-100">
                      <Calendar className="w-3.5 h-3.5 text-slate-500" />
                    </span>
                    {dt.appointmentHistory}
                  </h5>
                  {selectedCustomer.bookings.length === 0 ? (
                    <div className="text-center py-10 rounded-xl bg-slate-50 border-2 border-dashed border-slate-200">
                      <Calendar className="w-10 h-10 text-slate-300 mx-auto mb-3" />
                      <p className="text-sm font-medium text-slate-500">
                        {dt.noAppointmentHistory}
                      </p>
                    </div>
                  ) : (
                    <div className="space-y-3 max-h-52 overflow-y-auto pr-2">
                      {selectedCustomer.bookings
                        .slice(0, 10)
                        .map((booking: any, idx: number) => (
                          <div
                            key={idx}
                            className="flex items-center justify-between p-4 rounded-xl bg-slate-50 hover:bg-slate-100 transition-colors"
                          >
                            <div className="flex items-center gap-3">
                              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-white border border-slate-200">
                                <Calendar className="w-5 h-5 text-slate-400" />
                              </div>
                              <div>
                                <p className="text-sm font-semibold text-slate-900">
                                  {booking.service || "Appointment"}
                                </p>
                                <p className="text-xs text-slate-500">
                                  {new Date(
                                    booking.appointmentDate,
                                  ).toLocaleDateString(
                                    isAr ? "ar-SA" : "en-US",
                                    {
                                      weekday: "short",
                                      month: "short",
                                      day: "numeric",
                                    },
                                  )}{" "}
                                  {booking.appointmentTime
                                    ? `at ${booking.appointmentTime}`
                                    : ""}
                                </p>
                              </div>
                            </div>
                            <span
                              className={`px-3 py-1.5 rounded-lg text-xs font-bold ${
                                booking.status === "completed"
                                  ? "bg-emerald-100 text-emerald-700"
                                  : booking.status === "confirmed"
                                    ? "bg-blue-100 text-blue-700"
                                    : booking.status === "cancelled"
                                      ? "bg-red-100 text-red-700"
                                      : "bg-amber-100 text-amber-700"
                              }`}
                            >
                              {booking.status}
                            </span>
                          </div>
                        ))}
                    </div>
                  )}
                </div>
              </div>

              {/* Footer */}
              <div className="px-8 py-6 bg-gradient-to-r from-slate-50 via-slate-100/50 to-slate-50 border-t border-slate-200">
                <div className="flex items-center justify-between gap-4">
                  <button
                    onClick={() => {
                      setShowDetailModal(false);
                      handleOpenEditModal(selectedCustomer);
                    }}
                    className="inline-flex items-center gap-2 px-5 py-3 rounded-xl border-2 border-slate-200 bg-white text-sm font-bold text-slate-600 hover:bg-slate-50 hover:border-slate-300 transition-all duration-200"
                  >
                    <Edit3 className="w-4 h-4" />
                    {dt.edit}
                  </button>
                  <div className="flex items-center gap-3">
                    <button className="inline-flex items-center gap-2 px-5 py-3 rounded-xl border-2 border-brand-green bg-brand-green/10 text-sm font-bold text-brand-green hover:bg-brand-green/20 transition-all duration-200">
                      <MessageSquare className="w-4 h-4" />
                      {dt.sendMessage}
                    </button>
                    <button className="inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 text-sm font-bold text-white shadow-lg shadow-brand-green/30 hover:shadow-brand-green/50 hover:-translate-y-0.5 transition-all duration-200">
                      <Calendar className="w-4 h-4" />
                      {dt.createAppointmentFor}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal - Premium Design */}
      {showDeleteModal && selectedCustomer && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center p-4"
          onClick={() => setShowDeleteModal(false)}
        >
          {/* Backdrop with solid overlay */}
          <div className="absolute inset-0 bg-slate-900/95 backdrop-blur-sm" />

          {/* Modal */}
          <div
            className="relative w-full max-w-sm transform transition-all duration-300 ease-out animate-fadeIn"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Red gradient ring for danger */}
            <div className="absolute -inset-1 bg-gradient-to-r from-red-500 via-rose-500 to-red-600 rounded-3xl opacity-20 blur-lg" />

            <div className="relative bg-white rounded-2xl shadow-2xl overflow-hidden">
              {/* Red accent bar */}
              <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-red-500 via-rose-500 to-red-600" />

              <div className="p-8 text-center">
                <div className="w-16 h-16 rounded-2xl bg-gradient-to-br from-red-500 to-rose-600 flex items-center justify-center mx-auto mb-5 shadow-lg shadow-red-500/30">
                  <Trash2 className="w-8 h-8 text-white" />
                </div>
                <h3 className="text-2xl font-bold text-slate-900 mb-2">
                  {dt.confirmDelete}
                </h3>
                <p className="text-sm text-slate-600 max-w-xs mx-auto">
                  {dt.confirmDeleteDesc}
                </p>
              </div>
              <div className="flex items-center gap-4 px-8 py-6 bg-gradient-to-r from-slate-50 via-slate-100/50 to-slate-50 border-t border-slate-200">
                <button
                  onClick={() => setShowDeleteModal(false)}
                  className="flex-1 px-5 py-3 rounded-xl border-2 border-slate-200 bg-white text-sm font-bold text-slate-600 hover:bg-slate-50 hover:border-slate-300 transition-all duration-200"
                >
                  {dt.cancelAction}
                </button>
                <button
                  onClick={handleDeleteCustomer}
                  disabled={isSaving}
                  className="flex-1 px-5 py-3 rounded-xl bg-gradient-to-r from-red-500 to-rose-600 text-sm font-bold text-white shadow-lg shadow-red-500/30 hover:shadow-red-500/50 hover:-translate-y-0.5 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:translate-y-0 inline-flex items-center justify-center gap-2"
                >
                  {isSaving && <Loader2 className="w-4 h-4 animate-spin" />}
                  {dt.deleteCustomer}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
