"use client";

import { useState, useCallback } from "react";
import { formatQty } from "@/lib/product-unit";
import {
  CreditCard,
  Plus,
  Trash2,
  User,
  Mail,
  Building2,
  Globe,
  MapPin,
  Hash,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { BusinessCardPreview } from "@/features/delivery-management/components/business-card-preview";
import type { BusinessCardCreateRequestDTO } from "../dtos/order.dto";
import type { DeliveryBusinessCardDTO } from "@/features/delivery-management/dtos/delivery-management.dto";

// ============================================
// Card Form Data (internal state)
// ============================================
interface CardFormData {
  name: string;
  title: string;
  email: string;
  company: string;
  address: string;
  website: string;
  quantity: string;
}

const EMPTY_CARD: CardFormData = {
  name: "",
  title: "",
  email: "",
  company: "",
  address: "",
  website: "",
  quantity: "",
};

// ============================================
// Convert form data to DeliveryBusinessCardDTO for preview
// ============================================
function toPreviewCard(
  card: CardFormData,
  index: number
): DeliveryBusinessCardDTO {
  return {
    id: `preview-${index}`,
    deliveryOrderItemId: "preview",
    cardNumber: index + 1,
    name: card.name || "Your Name",
    title: card.title || null,
    email: card.email || "email@example.com",
    company: card.company || null,
    address: card.address || null,
    website: card.website || null,
    quantity: Number(card.quantity) || 0,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  };
}

// ============================================
// Single Card Entry (Form + Live Preview)
// ============================================
function CardEntry({
  card,
  index,
  total,
  onChange,
  onRemove,
  canRemove,
}: {
  card: CardFormData;
  index: number;
  total: number;
  onChange: (index: number, field: keyof CardFormData, value: string) => void;
  onRemove: (index: number) => void;
  canRemove: boolean;
}) {
  const previewCard = toPreviewCard(card, index);
  const hasData = card.name.trim() || card.email.trim();

  return (
    <div className="rounded-xl border border-gray-200 bg-white p-4">
      <div className="mb-3 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <div className="flex h-7 w-7 items-center justify-center rounded-full bg-[#1a6b5a]/10 text-xs font-bold text-[#1a6b5a]">
            {index + 1}
          </div>
          <h4 className="text-sm font-semibold text-gray-900">
            Card {index + 1}
          </h4>
          {card.quantity && (
            <span className="rounded-full bg-[#1a6b5a]/10 px-2 py-0.5 text-[10px] font-bold text-[#1a6b5a]">
              ×{formatQty(Number(card.quantity))}
            </span>
          )}
        </div>
        {canRemove && (
          <button
            type="button"
            onClick={() => onRemove(index)}
            className="rounded-lg p-1 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
          >
            <Trash2 className="h-4 w-4" />
          </button>
        )}
      </div>

      <div className="grid gap-4 lg:grid-cols-2">
        {/* Left: Form Fields */}
        <div className="space-y-3">
          {/* Name */}
          <div className="space-y-1">
            <label className="block text-xs font-medium text-gray-600">
              Full Name <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <User className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-gray-400" />
              <input
                type="text"
                value={card.name}
                onChange={(e) => onChange(index, "name", e.target.value)}
                placeholder="John Smith"
                className="block w-full rounded-lg border border-gray-200 bg-gray-50 py-2 pl-9 pr-3 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500"
              />
            </div>
          </div>

          {/* Title */}
          <div className="space-y-1">
            <label className="block text-xs font-medium text-gray-600">
              Job Title
            </label>
            <div className="relative">
              <Building2 className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-gray-400" />
              <input
                type="text"
                value={card.title}
                onChange={(e) => onChange(index, "title", e.target.value)}
                placeholder="CEO, Manager, etc."
                className="block w-full rounded-lg border border-gray-200 bg-gray-50 py-2 pl-9 pr-3 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500"
              />
            </div>
          </div>

          {/* Email */}
          <div className="space-y-1">
            <label className="block text-xs font-medium text-gray-600">
              Email <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <Mail className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-gray-400" />
              <input
                type="email"
                value={card.email}
                onChange={(e) => onChange(index, "email", e.target.value)}
                placeholder="john@example.com"
                className="block w-full rounded-lg border border-gray-200 bg-gray-50 py-2 pl-9 pr-3 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500"
              />
            </div>
          </div>

          {/* Company */}
          <div className="space-y-1">
            <label className="block text-xs font-medium text-gray-600">
              Company
            </label>
            <div className="relative">
              <Building2 className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-gray-400" />
              <input
                type="text"
                value={card.company}
                onChange={(e) => onChange(index, "company", e.target.value)}
                placeholder="Company Name"
                className="block w-full rounded-lg border border-gray-200 bg-gray-50 py-2 pl-9 pr-3 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500"
              />
            </div>
          </div>

          {/* Website */}
          <div className="space-y-1">
            <label className="block text-xs font-medium text-gray-600">
              Website
            </label>
            <div className="relative">
              <Globe className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-gray-400" />
              <input
                type="url"
                value={card.website}
                onChange={(e) => onChange(index, "website", e.target.value)}
                placeholder="www.example.com"
                className="block w-full rounded-lg border border-gray-200 bg-gray-50 py-2 pl-9 pr-3 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500"
              />
            </div>
          </div>

          {/* Address */}
          <div className="space-y-1">
            <label className="block text-xs font-medium text-gray-600">
              Address
            </label>
            <div className="relative">
              <MapPin className="absolute left-3 top-3 h-3.5 w-3.5 text-gray-400" />
              <textarea
                value={card.address}
                onChange={(e) => onChange(index, "address", e.target.value)}
                placeholder="123 Main St, Suite 100"
                rows={2}
                className="block w-full resize-none rounded-lg border border-gray-200 bg-gray-50 py-2 pl-9 pr-3 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500"
              />
            </div>
          </div>

          {/* Quantity */}
          <div className="space-y-1">
            <label className="block text-xs font-medium text-gray-600">
              Quantity <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <Hash className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-gray-400" />
              <input
                type="number"
                min="1"
                value={card.quantity}
                onChange={(e) => onChange(index, "quantity", e.target.value)}
                placeholder="e.g. 250"
                className="block w-full rounded-lg border border-gray-200 bg-gray-50 py-2 pl-9 pr-3 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500"
              />
            </div>
          </div>
        </div>

        {/* Right: Live Preview */}
        <div className="flex flex-col items-center justify-start">
          <p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-gray-400">
            Live Preview
          </p>
          {hasData ? (
            <BusinessCardPreview card={previewCard} format="both" />
          ) : (
            <div className="flex min-h-64 w-full max-w-[400px] flex-col items-center justify-center rounded-lg border-2 border-dashed border-gray-200 bg-gray-50 p-4 sm:min-h-[460px]">
              <CreditCard className="mb-2 h-8 w-8 text-gray-300" />
              <p className="text-xs text-gray-400">
                Fill in name & email to see preview
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ============================================
// Inline Business Card Section Props
// ============================================
interface InlineBusinessCardProps {
  cards: BusinessCardCreateRequestDTO[];
  onChange: (cards: BusinessCardCreateRequestDTO[]) => void;
}

// ============================================
// Inline Business Card Section
// ============================================
export function InlineBusinessCard({
  cards,
  onChange,
}: InlineBusinessCardProps) {
  // Convert DTOs to form data
  const [formData, setFormData] = useState<CardFormData[]>(() => {
    if (cards.length > 0) {
      return cards.map((bc) => ({
        name: bc.name,
        title: bc.title ?? "",
        email: bc.email,
        company: bc.company ?? "",
        address: bc.address ?? "",
        website: bc.website ?? "",
        quantity: String(bc.quantity ?? ""),
      }));
    }
    // Start with 3 empty cards
    return [{ ...EMPTY_CARD }, { ...EMPTY_CARD }, { ...EMPTY_CARD }];
  });

  // Sync parent when formData changes
  const syncToParent = useCallback(
    (data: CardFormData[]) => {
      const dtos: BusinessCardCreateRequestDTO[] = data
        .filter((card) => card.name.trim() || card.email.trim())
        .map((card, idx) => ({
          orderItemId: "",
          cardNumber: idx + 1,
          name: card.name.trim(),
          title: card.title.trim() || null,
          email: card.email.trim(),
          company: card.company.trim() || null,
          address: card.address.trim() || null,
          website: card.website.trim() || null,
          quantity: Number(card.quantity) || 1,
        }));
      onChange(dtos);
    },
    [onChange]
  );

  const handleChange = useCallback(
    (index: number, field: keyof CardFormData, value: string) => {
      setFormData((prev) => {
        const next = prev.map((card, i) =>
          i === index ? { ...card, [field]: value } : card
        );
        // Debounce sync to parent
        setTimeout(() => syncToParent(next), 0);
        return next;
      });
    },
    [syncToParent]
  );

  const handleRemove = useCallback(
    (index: number) => {
      setFormData((prev) => {
        const next = prev.filter((_, i) => i !== index);
        setTimeout(() => syncToParent(next), 0);
        return next;
      });
    },
    [syncToParent]
  );

  const handleAdd = useCallback(() => {
    setFormData((prev) => {
      const next = [...prev, { ...EMPTY_CARD }];
      setTimeout(() => syncToParent(next), 0);
      return next;
    });
  }, [syncToParent]);

  const totalCopies = formData.reduce(
    (sum, card) => sum + (Number(card.quantity) || 0),
    0
  );

  return (
    <div className="space-y-4">
      {/* Section Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <CreditCard className="h-4 w-4 text-[#1a6b5a]" />
          <span className="text-sm font-medium text-gray-700">
            Business Cards ({formData.length})
          </span>
          {totalCopies > 0 && (
            <span className="rounded-full bg-[#1a6b5a]/10 px-2 py-0.5 text-[10px] font-bold text-[#1a6b5a]">
              {totalCopies.toLocaleString()} total copies
            </span>
          )}
        </div>
      </div>

      {/* Card Entries */}
      <div className="space-y-4">
        {formData.map((card, index) => (
          <CardEntry
            key={index}
            card={card}
            index={index}
            total={formData.length}
            onChange={handleChange}
            onRemove={handleRemove}
            canRemove={formData.length > 1}
          />
        ))}
      </div>

      {/* Add Card Button */}
      {(
        <button
          type="button"
          onClick={handleAdd}
          className="flex w-full items-center justify-center gap-2 rounded-lg border-2 border-dashed border-[#1a6b5a]/30 py-3 text-sm font-medium text-[#1a6b5a] transition-colors hover:border-[#1a6b5a] hover:bg-[#1a6b5a]/5"
        >
          <Plus className="h-4 w-4" />
          Add Another Business Card
        </button>
      )}
    </div>
  );
}
