"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import {
  AlertTriangle,
  CheckCircle2,
  Clock,
  CreditCard,
  ExternalLink,
  Eye,
  Filter,
  Loader2,
  Mail,
  MapPin,
  Package,
  Phone,
  RefreshCw,
  Save,
  Search,
  ShoppingCart,
  Truck,
  User,
  X,
  XCircle,
} from "lucide-react";
import { formatPrice } from "@/lib/format";

type OrderItem = {
  productId: number;
  name: string;
  brand: string;
  image: string;
  price: number;
  qty: number;
};

type Order = {
  id: number;
  orderNo: string;
  customerId: number | null;
  customerName: string;
  email: string;
  phone: string;
  city: string;
  address: string;
  note: string | null;
  paymentMethod: string;
  paymentStatus: string;
  cardLast4: string | null;
  cardBrand: string | null;
  shippingMethod: string;
  cargoTrackingCode: string | null;
  cargoProvider: string | null;
  items: OrderItem[];
  subtotal: number;
  shipping: number;
  total: number;
  status: "hazirlaniyor" | "kargoda" | "teslim_edildi" | "iptal";
  createdAt: string;
};

const statusBadge: Record<string, { bg: string; text: string; label: string }> = {
  hazirlaniyor: { bg: "bg-amber-100", text: "text-amber-800", label: "Hazırlanıyor" },
  kargoda: { bg: "bg-blue-100", text: "text-blue-800", label: "Kargoda" },
  teslim_edildi: { bg: "bg-emerald-100", text: "text-emerald-800", label: "Teslim Edildi" },
  iptal: { bg: "bg-red-100", text: "text-red-800", label: "İptal Edildi" },
};

const paymentBadge: Record<string, { bg: string; text: string; label: string }> = {
  odendi: { bg: "bg-emerald-50", text: "text-emerald-700", label: "Ödendi" },
  odeme_bekleniyor: { bg: "bg-amber-50", text: "text-amber-700", label: "Havale Bekleniyor" },
  kapida_odeme: { bg: "bg-blue-50", text: "text-blue-700", label: "Kapıda Ödeme" },
};

const CARGO_PROVIDERS = [
  { id: "aras", name: "Aras Kargo" },
  { id: "yurtici", name: "Yurtiçi Kargo" },
  { id: "mng", name: "MNG Kargo" },
  { id: "ptt", name: "PTT Kargo" },
  { id: "surat", name: "Sürat Kargo" },
];

export default function AdminOrdersPage() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");

  // Detay Modal State
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [newStatus, setNewStatus] = useState<Order["status"]>("hazirlaniyor");
  const [newTrackingCode, setNewTrackingCode] = useState("");
  const [newCargoProvider, setNewCargoProvider] = useState("aras");
  const [updating, setUpdating] = useState(false);
  const [updateSuccess, setUpdateSuccess] = useState(false);

  async function fetchOrders() {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (statusFilter !== "all") params.set("status", statusFilter);
      if (searchTerm.trim()) params.set("search", searchTerm.trim());

      const res = await fetch(`/api/admin/orders?${params.toString()}`);
      const data = await res.json();
      if (data?.orders) {
        setOrders(data.orders);
      }
    } catch (err) {
      console.error("Siparişler yüklenemedi:", err);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    fetchOrders();
  }, [statusFilter]);

  function handleSearch(e: React.FormEvent) {
    e.preventDefault();
    fetchOrders();
  }

  function openDetailModal(order: Order) {
    setSelectedOrder(order);
    setNewStatus(order.status);
    setNewTrackingCode(order.cargoTrackingCode || "");
    setNewCargoProvider(order.cargoProvider || order.shippingMethod || "aras");
    setUpdateSuccess(false);
    setModalOpen(true);
  }

  async function handleUpdateOrder() {
    if (!selectedOrder) return;
    setUpdating(true);
    setUpdateSuccess(false);
    try {
      const res = await fetch(`/api/admin/orders/${selectedOrder.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          status: newStatus,
          cargoTrackingCode: newTrackingCode,
          cargoProvider: newCargoProvider,
        }),
      });
      const data = await res.json();
      if (res.ok && data?.order) {
        setUpdateSuccess(true);
        setSelectedOrder(data.order);
        // Listeyi güncelle
        setOrders((prev) =>
          prev.map((o) => (o.id === data.order.id ? data.order : o))
        );
        setTimeout(() => setUpdateSuccess(false), 2500);
      } else {
        alert(data.error || "Güncelleme başarısız.");
      }
    } catch {
      alert("Bağlantı hatası.");
    } finally {
      setUpdating(false);
    }
  }

  return (
    <div className="space-y-6">
      {/* Başlık ve İstatistikler */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-3">
          <div className="grid size-12 place-items-center rounded-2xl bg-gradient-to-br from-brand-400 to-brand-600 text-white shadow-lg shadow-brand-500/25">
            <ShoppingCart className="size-6" />
          </div>
          <div>
            <h2 className="text-2xl font-black text-ink">Sipariş Yönetimi</h2>
            <p className="text-sm font-bold text-mocha">
              Gelen siparişleri inceleyin, durumlarını değiştirin ve kargo takip numarası girin
            </p>
          </div>
        </div>

        <button
          type="button"
          onClick={fetchOrders}
          className="flex items-center gap-1.5 rounded-xl border border-slate-200 bg-white px-3.5 py-2 text-xs font-extrabold text-ink shadow-sm transition hover:bg-slate-50"
        >
          <RefreshCw className={`size-3.5 text-mocha ${loading ? "animate-spin" : ""}`} />
          Yenile
        </button>
      </div>

      {/* Arama ve Filtreleme Barı */}
      <div className="flex flex-col gap-3 rounded-2xl bg-white p-4 shadow-sm ring-1 ring-slate-200 sm:flex-row sm:items-center sm:justify-between">
        {/* Durum Filtre Butonları */}
        <div className="flex flex-wrap items-center gap-1.5">
          {[
            { id: "all", label: "Tümü" },
            { id: "hazirlaniyor", label: "Hazırlanıyor" },
            { id: "kargoda", label: "Kargoda" },
            { id: "teslim_edildi", label: "Teslim Edildi" },
            { id: "iptal", label: "İptal" },
          ].map((tab) => (
            <button
              key={tab.id}
              type="button"
              onClick={() => setStatusFilter(tab.id)}
              className={`rounded-xl px-3 py-1.5 text-xs font-extrabold transition ${
                statusFilter === tab.id
                  ? "bg-ink text-white shadow-sm"
                  : "bg-slate-50 text-mocha hover:bg-slate-100 hover:text-ink"
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>

        {/* Arama Formu */}
        <form onSubmit={handleSearch} className="relative flex items-center">
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder="Sipariş No, Müşteri, Telefon..."
            className="w-full rounded-xl border border-slate-200 bg-slate-50 py-2 pl-9 pr-3 text-xs font-bold text-ink outline-none transition focus:border-brand-500 focus:bg-white sm:w-64"
          />
          <Search className="pointer-events-none absolute left-3 size-4 text-mocha" />
        </form>
      </div>

      {/* Sipariş Tablosu */}
      <div className="overflow-hidden rounded-2xl bg-white shadow-sm ring-1 ring-slate-200">
        {loading ? (
          <div className="flex h-64 flex-col items-center justify-center gap-3">
            <Loader2 className="size-8 animate-spin text-brand-500" />
            <span className="text-xs font-bold text-mocha">Siparişler yükleniyor...</span>
          </div>
        ) : orders.length === 0 ? (
          <div className="flex flex-col items-center justify-center gap-3 py-16 text-center">
            <Package className="size-16 text-slate-300" />
            <p className="text-lg font-extrabold text-ink">Eşleşen sipariş bulunamadı</p>
            <p className="text-xs text-mocha">Arama kriterlerinizi değiştirmeyi deneyin.</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-left text-sm">
              <thead>
                <tr className="border-b border-slate-200 bg-slate-50/80">
                  <th className="px-4 py-3.5 font-extrabold text-mocha">Sipariş No</th>
                  <th className="px-4 py-3.5 font-extrabold text-mocha">Müşteri</th>
                  <th className="px-4 py-3.5 font-extrabold text-mocha">Şehir</th>
                  <th className="px-4 py-3.5 font-extrabold text-mocha">Tutar</th>
                  <th className="px-4 py-3.5 font-extrabold text-mocha">Ödeme</th>
                  <th className="px-4 py-3.5 font-extrabold text-mocha">Durum</th>
                  <th className="px-4 py-3.5 font-extrabold text-mocha">Kargo Takip</th>
                  <th className="px-4 py-3.5 font-extrabold text-mocha">Tarih</th>
                  <th className="px-4 py-3.5 text-right font-extrabold text-mocha">İşlem</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100 font-sans">
                {orders.map((o) => {
                  const sb = statusBadge[o.status] || {
                    bg: "bg-slate-100",
                    text: "text-slate-700",
                    label: o.status,
                  };
                  const pb = paymentBadge[o.paymentStatus] || {
                    bg: "bg-slate-100",
                    text: "text-slate-700",
                    label: o.paymentStatus,
                  };

                  return (
                    <tr
                      key={o.id}
                      className="cursor-pointer transition hover:bg-slate-50/80"
                      onClick={() => openDetailModal(o)}
                    >
                      <td className="px-4 py-3 font-mono font-black text-brand-600">
                        {o.orderNo}
                      </td>
                      <td className="px-4 py-3">
                        <p className="font-extrabold text-ink">{o.customerName}</p>
                        <p className="text-[11px] font-bold text-mocha">{o.phone}</p>
                      </td>
                      <td className="px-4 py-3 font-bold text-cocoa">{o.city}</td>
                      <td className="px-4 py-3 font-black text-brand-600">
                        {formatPrice(o.total)}
                      </td>
                      <td className="px-4 py-3">
                        <span
                          className={`inline-block rounded-md px-2 py-0.5 text-[10px] font-extrabold ${pb.bg} ${pb.text}`}
                        >
                          {pb.label}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <span
                          className={`inline-block rounded-full px-2.5 py-1 text-xs font-extrabold ${sb.bg} ${sb.text}`}
                        >
                          {sb.label}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        {o.cargoTrackingCode ? (
                          <span className="font-mono text-xs font-bold text-indigo-600">
                            {o.cargoTrackingCode}
                          </span>
                        ) : (
                          <span className="text-xs text-slate-400">—</span>
                        )}
                      </td>
                      <td className="px-4 py-3 text-xs font-bold text-mocha">
                        {new Date(o.createdAt).toLocaleDateString("tr-TR", {
                          day: "2-digit",
                          month: "short",
                          hour: "2-digit",
                          minute: "2-digit",
                        })}
                      </td>
                      <td className="px-4 py-3 text-right">
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            openDetailModal(o);
                          }}
                          className="inline-flex items-center gap-1 rounded-xl bg-slate-100 px-3 py-1.5 text-xs font-extrabold text-ink transition hover:bg-brand-500 hover:text-white"
                        >
                          <Eye className="size-3.5" />
                          Detay
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* SİPARİŞ DETAY & YÖNETİM MODALI */}
      {modalOpen && selectedOrder && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div
            className="fixed inset-0 bg-ink/50 backdrop-blur-sm transition-opacity"
            onClick={() => setModalOpen(false)}
          />

          <div className="relative max-h-[90vh] w-full max-w-3xl overflow-y-auto rounded-3xl bg-white p-6 shadow-2xl ring-1 ring-slate-200">
            {/* Modal Header */}
            <div className="flex items-center justify-between border-b border-slate-100 pb-4">
              <div>
                <div className="flex items-center gap-2">
                  <h3 className="font-display text-xl font-black text-ink">
                    Sipariş #{selectedOrder.orderNo}
                  </h3>
                  <span
                    className={`rounded-full px-2.5 py-0.5 text-xs font-extrabold ${
                      statusBadge[selectedOrder.status]?.bg
                    } ${statusBadge[selectedOrder.status]?.text}`}
                  >
                    {statusBadge[selectedOrder.status]?.label}
                  </span>
                </div>
                <p className="text-xs font-bold text-mocha">
                  {new Date(selectedOrder.createdAt).toLocaleString("tr-TR")}
                </p>
              </div>

              <button
                type="button"
                onClick={() => setModalOpen(false)}
                className="grid size-9 place-items-center rounded-xl text-mocha hover:bg-slate-100 hover:text-ink transition"
              >
                <X className="size-5" />
              </button>
            </div>

            {/* Modal İçeriği */}
            <div className="mt-6 space-y-6">
              {/* Durum Değiştirme ve Kargo Yönetimi Kartı */}
              <div className="rounded-2xl border border-indigo-100 bg-indigo-50/50 p-4">
                <h4 className="flex items-center gap-2 font-display text-sm font-extrabold text-indigo-950">
                  <Truck className="size-4 text-indigo-600" />
                  Sipariş Durumu & Kargo Takip Bilgisi
                </h4>

                <div className="mt-4 grid gap-3 sm:grid-cols-3">
                  {/* Durum Seçimi */}
                  <div>
                    <label className="mb-1 block text-xs font-extrabold uppercase tracking-wider text-indigo-900">
                      Sipariş Durumu
                    </label>
                    <select
                      value={newStatus}
                      onChange={(e) => setNewStatus(e.target.value as any)}
                      className="w-full rounded-xl border border-indigo-200 bg-white px-3 py-2 text-xs font-extrabold text-ink outline-none focus:border-indigo-500"
                    >
                      <option value="hazirlaniyor">Hazırlanıyor</option>
                      <option value="kargoda">Kargoda (Kargoya Verildi)</option>
                      <option value="teslim_edildi">Teslim Edildi</option>
                      <option value="iptal">İptal Edildi</option>
                    </select>
                  </div>

                  {/* Kargo Firması */}
                  <div>
                    <label className="mb-1 block text-xs font-extrabold uppercase tracking-wider text-indigo-900">
                      Kargo Firması
                    </label>
                    <select
                      value={newCargoProvider}
                      onChange={(e) => setNewCargoProvider(e.target.value)}
                      className="w-full rounded-xl border border-indigo-200 bg-white px-3 py-2 text-xs font-extrabold text-ink outline-none focus:border-indigo-500"
                    >
                      {CARGO_PROVIDERS.map((c) => (
                        <option key={c.id} value={c.id}>
                          {c.name}
                        </option>
                      ))}
                    </select>
                  </div>

                  {/* Kargo Takip No */}
                  <div>
                    <label className="mb-1 block text-xs font-extrabold uppercase tracking-wider text-indigo-900">
                      Kargo Takip No
                    </label>
                    <input
                      type="text"
                      value={newTrackingCode}
                      onChange={(e) => setNewTrackingCode(e.target.value)}
                      placeholder="Örn: 1234567890"
                      className="w-full rounded-xl border border-indigo-200 bg-white px-3 py-2 font-mono text-xs font-bold text-ink outline-none focus:border-indigo-500"
                    />
                  </div>
                </div>

                <div className="mt-4 flex items-center justify-end gap-3">
                  <button
                    type="button"
                    onClick={handleUpdateOrder}
                    disabled={updating}
                    className="flex items-center gap-1.5 rounded-xl bg-indigo-600 px-4 py-2 text-xs font-extrabold text-white shadow-md shadow-indigo-600/20 transition hover:bg-indigo-700 disabled:opacity-50"
                  >
                    {updating ? (
                      <Loader2 className="size-3.5 animate-spin" />
                    ) : updateSuccess ? (
                      <CheckCircle2 className="size-3.5" />
                    ) : (
                      <Save className="size-3.5" />
                    )}
                    {updateSuccess ? "Güncellendi!" : "Değişiklikleri Kaydet"}
                  </button>
                </div>
              </div>

              {/* Müşteri ve Teslimat Bilgileri */}
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                  <h4 className="flex items-center gap-1.5 text-xs font-extrabold uppercase tracking-wider text-mocha">
                    <User className="size-3.5" /> Müşteri Bilgileri
                  </h4>
                  <div className="mt-3 space-y-1.5 text-xs font-bold text-ink">
                    <p className="text-sm font-extrabold">{selectedOrder.customerName}</p>
                    <p className="flex items-center gap-1.5 text-mocha">
                      <Phone className="size-3.5 text-slate-400" /> {selectedOrder.phone}
                    </p>
                    <p className="flex items-center gap-1.5 text-mocha">
                      <Mail className="size-3.5 text-slate-400" /> {selectedOrder.email}
                    </p>
                  </div>
                </div>

                <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                  <h4 className="flex items-center gap-1.5 text-xs font-extrabold uppercase tracking-wider text-mocha">
                    <MapPin className="size-3.5" /> Teslimat Adresi
                  </h4>
                  <div className="mt-3 space-y-1 text-xs font-bold text-ink">
                    <p className="font-extrabold text-cocoa">{selectedOrder.city}</p>
                    <p className="text-mocha leading-relaxed">{selectedOrder.address}</p>
                    {selectedOrder.note && (
                      <p className="mt-2 rounded-lg bg-amber-50 p-2 text-[11px] font-semibold text-amber-800">
                        <strong>Müşteri Notu:</strong> {selectedOrder.note}
                      </p>
                    )}
                  </div>
                </div>
              </div>

              {/* Sipariş Edilen Ürünler */}
              <div className="rounded-2xl border border-slate-200 bg-white p-4">
                <h4 className="text-xs font-extrabold uppercase tracking-wider text-mocha">
                  Siparişteki Ürünler ({selectedOrder.items?.length ?? 0} Kalem)
                </h4>

                <div className="mt-3 divide-y divide-slate-100">
                  {selectedOrder.items?.map((item, idx) => (
                    <div key={idx} className="flex items-center justify-between py-3">
                      <div className="flex items-center gap-3">
                        <div className="relative size-12 shrink-0 overflow-hidden rounded-xl bg-slate-100">
                          {item.image && (
                            <Image
                              src={item.image}
                              alt={item.name}
                              fill
                              sizes="48px"
                              className="object-cover"
                            />
                          )}
                        </div>
                        <div>
                          <p className="font-extrabold text-ink line-clamp-1">{item.name}</p>
                          <p className="text-[11px] font-bold text-mocha">
                            {item.brand} · {item.qty} adet × {formatPrice(item.price)}
                          </p>
                        </div>
                      </div>
                      <span className="font-mono text-sm font-extrabold text-brand-600">
                        {formatPrice(item.price * item.qty)}
                      </span>
                    </div>
                  ))}
                </div>

                {/* Tutar Özeti */}
                <div className="mt-4 border-t border-slate-100 pt-3 space-y-1 text-xs font-bold">
                  <div className="flex justify-between text-mocha">
                    <span>Ara Toplam:</span>
                    <span>{formatPrice(selectedOrder.subtotal)}</span>
                  </div>
                  <div className="flex justify-between text-mocha">
                    <span>Kargo Ücreti:</span>
                    <span>{selectedOrder.shipping === 0 ? "Ücretsiz" : formatPrice(selectedOrder.shipping)}</span>
                  </div>
                  <div className="flex justify-between border-t border-slate-200 pt-2 text-sm font-black text-ink">
                    <span>Genel Toplam:</span>
                    <span className="text-brand-600">{formatPrice(selectedOrder.total)}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
