"use client";

import { useEffect, useState } from "react";
import {
  Search,
  X,
  DollarSign,
  Clock,
  CheckCircle,
  XCircle,
  AlertTriangle,
  Plus,
  Eye,
  Ban,
  RefreshCw,
  User,
  CreditCard,
  FileText,
} from "lucide-react";

interface Refund {
  id: string;
  stripeRefundId: string;
  stripePaymentIntentId: string | null;
  stripeChargeId: string | null;
  customerId: string;
  userId: string | null;
  amount: number;
  amountFormatted: string;
  currency: string;
  status: "pending" | "succeeded" | "failed" | "canceled";
  reason: string | null;
  stripeReason: string | null;
  staffId: string | null;
  staffNotes: string | null;
  customerReason: string | null;
  failureReason: string | null;
  createdAt: string;
  processedAt: string | null;
  user: {
    id: string;
    email: string;
    name: string;
    companyName: string | null;
  } | null;
  subscription: {
    id: string;
    tierId: string;
    status: string;
  } | null;
}

interface RefundablePayment {
  paymentIntentId: string;
  chargeId: string | null;
  amount: number;
  amountFormatted: string;
  amountRefunded: number;
  amountRefundedFormatted: string;
  amountRefundable: number;
  amountRefundableFormatted: string;
  currency: string;
  status: string;
  description: string | null;
  created: string;
}

interface User {
  id: string;
  role: string;
  name: string;
}

export default function RefundsList({ user }: { user: User }) {
  const [refunds, setRefunds] = useState<Refund[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState({
    status: "all",
    search: "",
  });
  const [selectedRefund, setSelectedRefund] = useState<Refund | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [toast, setToast] = useState<{
    message: string;
    type: "success" | "error";
  } | null>(null);

  // Create refund form state
  const [createForm, setCreateForm] = useState({
    customerId: "",
    paymentIntentId: "",
    chargeId: "",
    amount: "",
    reason: "requested_by_customer" as
      | "requested_by_customer"
      | "duplicate"
      | "fraudulent",
    customerReason: "",
    staffNotes: "",
    isPartial: false,
  });
  const [refundablePayments, setRefundablePayments] = useState<
    RefundablePayment[]
  >([]);
  const [loadingPayments, setLoadingPayments] = useState(false);
  const [creating, setCreating] = useState(false);

  const canProcessRefunds =
    user.role === "ADMIN" || user.role === "SUPER_ADMIN";

  const fetchRefunds = async () => {
    try {
      const params = new URLSearchParams();
      if (filter.status !== "all") params.append("status", filter.status);

      const response = await fetch(`/api/staff/dashboard/refunds?${params}`);
      if (response.ok) {
        const data = await response.json();
        setRefunds(data.refunds);
      }
    } catch (error) {
      console.error("Failed to fetch refunds:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRefunds();
  }, [filter]);

  // Fetch refundable payments when customer ID changes
  const fetchRefundablePayments = async (customerId: string) => {
    if (!customerId) {
      setRefundablePayments([]);
      return;
    }

    setLoadingPayments(true);
    try {
      const response = await fetch(
        `/api/staff/dashboard/refunds/refundable?customerId=${customerId}`,
      );
      if (response.ok) {
        const data = await response.json();
        setRefundablePayments(data.payments);
      }
    } catch (error) {
      console.error("Failed to fetch refundable payments:", error);
    } finally {
      setLoadingPayments(false);
    }
  };

  const handleCreateRefund = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!canProcessRefunds) return;

    setCreating(true);
    try {
      const response = await fetch("/api/staff/dashboard/refunds", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          paymentIntentId: createForm.paymentIntentId || undefined,
          chargeId: createForm.chargeId || undefined,
          amount:
            createForm.isPartial && createForm.amount
              ? parseInt(createForm.amount) * 100
              : undefined,
          reason: createForm.reason,
          customerReason: createForm.customerReason || undefined,
          staffNotes: createForm.staffNotes || undefined,
          customerId: createForm.customerId,
        }),
      });

      const data = await response.json();

      if (response.ok) {
        setToast({
          message: `Refund created successfully: ${data.refund.amountFormatted} ${data.refund.currency.toUpperCase()}`,
          type: "success",
        });
        setShowCreateModal(false);
        resetCreateForm();
        fetchRefunds();
      } else {
        setToast({
          message: data.error || "Failed to create refund",
          type: "error",
        });
      }
    } catch (error) {
      console.error("Failed to create refund:", error);
      setToast({ message: "Failed to create refund", type: "error" });
    } finally {
      setCreating(false);
    }
  };

  const handleCancelRefund = async (refundId: string) => {
    if (!canProcessRefunds) return;

    try {
      const response = await fetch(
        `/api/staff/dashboard/refunds/${refundId}/cancel`,
        {
          method: "POST",
        },
      );

      const data = await response.json();

      if (response.ok) {
        setToast({ message: "Refund cancelled successfully", type: "success" });
        fetchRefunds();
        setSelectedRefund(null);
      } else {
        setToast({
          message: data.error || "Failed to cancel refund",
          type: "error",
        });
      }
    } catch (error) {
      console.error("Failed to cancel refund:", error);
      setToast({ message: "Failed to cancel refund", type: "error" });
    }
  };

  const resetCreateForm = () => {
    setCreateForm({
      customerId: "",
      paymentIntentId: "",
      chargeId: "",
      amount: "",
      reason: "requested_by_customer",
      customerReason: "",
      staffNotes: "",
      isPartial: false,
    });
    setRefundablePayments([]);
  };

  // Auto-dismiss toast after 5 seconds
  useEffect(() => {
    if (toast) {
      const timer = setTimeout(() => setToast(null), 5000);
      return () => clearTimeout(timer);
    }
  }, [toast]);

  const getStatusBadge = (status: string) => {
    const styles: Record<string, { bg: string; icon: React.ReactNode }> = {
      pending: {
        bg: "bg-yellow-100 text-yellow-800",
        icon: <Clock className="w-3 h-3" />,
      },
      succeeded: {
        bg: "bg-green-100 text-green-800",
        icon: <CheckCircle className="w-3 h-3" />,
      },
      failed: {
        bg: "bg-red-100 text-red-800",
        icon: <XCircle className="w-3 h-3" />,
      },
      canceled: {
        bg: "bg-gray-100 text-gray-800",
        icon: <Ban className="w-3 h-3" />,
      },
    };

    const style = styles[status] || styles.pending;

    return (
      <span
        className={`inline-flex items-center gap-1 px-2 py-1 text-xs font-medium rounded-full ${style.bg}`}
      >
        {style.icon}
        {status.charAt(0).toUpperCase() + status.slice(1)}
      </span>
    );
  };

  const getReasonLabel = (reason: string | null) => {
    const labels: Record<string, string> = {
      requested_by_customer: "Customer Request",
      duplicate: "Duplicate Charge",
      fraudulent: "Fraudulent",
    };
    return reason ? labels[reason] || reason : "Not specified";
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString("en-GB", {
      day: "2-digit",
      month: "short",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-primary"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Toast */}
      {toast && (
        <div
          className={`fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg ${
            toast.type === "success" ? "bg-green-500" : "bg-red-500"
          } text-white flex items-center gap-2`}
        >
          {toast.type === "success" ? (
            <CheckCircle className="w-5 h-5" />
          ) : (
            <AlertTriangle className="w-5 h-5" />
          )}
          {toast.message}
          <button type="button" aria-label="Dismiss" onClick={() => setToast(null)} className="ml-2">
            <X className="w-4 h-4" />
          </button>
        </div>
      )}

      {/* Filters and Actions */}
      <div className="flex flex-col sm:flex-row gap-4 justify-between">
        <div className="flex flex-col sm:flex-row gap-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
            <input
              type="text"
              placeholder="Search by customer ID..."
              value={filter.search}
              onChange={(e) => setFilter({ ...filter, search: e.target.value })}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-primary focus:border-transparent"
            />
          </div>
          <select
            value={filter.status}
            onChange={(e) => setFilter({ ...filter, status: e.target.value })}
            className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-primary focus:border-transparent"
          >
            <option value="all">All Status</option>
            <option value="pending">Pending</option>
            <option value="succeeded">Succeeded</option>
            <option value="failed">Failed</option>
            <option value="canceled">Cancelled</option>
          </select>
        </div>

        <div className="flex gap-2">
          <button
            onClick={fetchRefunds}
            className="flex items-center gap-2 px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
          >
            <RefreshCw className="w-4 h-4" />
            Refresh
          </button>
          {canProcessRefunds && (
            <button
              onClick={() => setShowCreateModal(true)}
              className="flex items-center gap-2 px-4 py-2 bg-brand-primary text-white rounded-lg hover:bg-brand-primary/90"
            >
              <Plus className="w-4 h-4" />
              New Refund
            </button>
          )}
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white p-4 rounded-lg shadow border">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-blue-100 rounded-lg">
              <DollarSign className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">Total Refunds</p>
              <p className="text-xl font-semibold">{refunds.length}</p>
            </div>
          </div>
        </div>
        <div className="bg-white p-4 rounded-lg shadow border">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-yellow-100 rounded-lg">
              <Clock className="w-5 h-5 text-yellow-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">Pending</p>
              <p className="text-xl font-semibold">
                {refunds.filter((r) => r.status === "pending").length}
              </p>
            </div>
          </div>
        </div>
        <div className="bg-white p-4 rounded-lg shadow border">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-green-100 rounded-lg">
              <CheckCircle className="w-5 h-5 text-green-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">Succeeded</p>
              <p className="text-xl font-semibold">
                {refunds.filter((r) => r.status === "succeeded").length}
              </p>
            </div>
          </div>
        </div>
        <div className="bg-white p-4 rounded-lg shadow border">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-red-100 rounded-lg">
              <XCircle className="w-5 h-5 text-red-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">Failed</p>
              <p className="text-xl font-semibold">
                {refunds.filter((r) => r.status === "failed").length}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Refunds Table */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        {refunds.length === 0 ? (
          <div className="p-8 text-center text-gray-500">
            <DollarSign className="w-12 h-12 mx-auto mb-4 text-gray-300" />
            <p>No refunds found</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Refund
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Customer
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Amount
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Status
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Reason
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Date
                  </th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {refunds.map((refund) => (
                  <tr key={refund.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm font-medium text-gray-900">
                        {refund.stripeRefundId.slice(0, 15)}...
                      </div>
                      <div className="text-xs text-gray-500">
                        {refund.stripePaymentIntentId?.slice(0, 15)}...
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      {refund.user ? (
                        <div>
                          <div className="text-sm font-medium text-gray-900">
                            {refund.user.name}
                          </div>
                          <div className="text-xs text-gray-500">
                            {refund.user.email}
                          </div>
                        </div>
                      ) : (
                        <div className="text-sm text-gray-500">
                          {refund.customerId.slice(0, 15)}...
                        </div>
                      )}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm font-semibold text-gray-900">
                        {refund.currency.toUpperCase()} {refund.amountFormatted}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      {getStatusBadge(refund.status)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className="text-sm text-gray-600">
                        {getReasonLabel(refund.reason)}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {formatDate(refund.createdAt)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => setSelectedRefund(refund)}
                          className="text-brand-primary hover:text-brand-primary/80"
                          title="View Details"
                        >
                          <Eye className="w-4 h-4" />
                        </button>
                        {refund.status === "pending" && canProcessRefunds && (
                          <button
                            onClick={() => handleCancelRefund(refund.id)}
                            className="text-red-600 hover:text-red-800"
                            title="Cancel Refund"
                          >
                            <Ban className="w-4 h-4" />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Refund Details Modal */}
      {selectedRefund && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6">
              <div className="flex justify-between items-start mb-6">
                <div>
                  <h2 className="text-xl font-bold text-gray-900">
                    Refund Details
                  </h2>
                  <p className="text-sm text-gray-500">
                    {selectedRefund.stripeRefundId}
                  </p>
                </div>
                <button
                  onClick={() => setSelectedRefund(null)}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <X className="w-6 h-6" />
                </button>
              </div>

              <div className="space-y-6">
                {/* Status and Amount */}
                <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <p className="text-sm text-gray-500">Amount</p>
                    <p className="text-2xl font-bold text-gray-900">
                      {selectedRefund.currency.toUpperCase()}{" "}
                      {selectedRefund.amountFormatted}
                    </p>
                  </div>
                  {getStatusBadge(selectedRefund.status)}
                </div>

                {/* Customer Info */}
                {selectedRefund.user && (
                  <div className="border rounded-lg p-4">
                    <h3 className="font-medium text-gray-900 mb-3 flex items-center gap-2">
                      <User className="w-4 h-4" /> Customer
                    </h3>
                    <div className="space-y-2 text-sm">
                      <p>
                        <span className="text-gray-500">Name:</span>{" "}
                        {selectedRefund.user.name}
                      </p>
                      <p>
                        <span className="text-gray-500">Email:</span>{" "}
                        {selectedRefund.user.email}
                      </p>
                      {selectedRefund.user.companyName && (
                        <p>
                          <span className="text-gray-500">Company:</span>{" "}
                          {selectedRefund.user.companyName}
                        </p>
                      )}
                    </div>
                  </div>
                )}

                {/* Payment Info */}
                <div className="border rounded-lg p-4">
                  <h3 className="font-medium text-gray-900 mb-3 flex items-center gap-2">
                    <CreditCard className="w-4 h-4" /> Payment Details
                  </h3>
                  <div className="space-y-2 text-sm">
                    <p>
                      <span className="text-gray-500">Payment Intent:</span>{" "}
                      {selectedRefund.stripePaymentIntentId || "N/A"}
                    </p>
                    <p>
                      <span className="text-gray-500">Charge ID:</span>{" "}
                      {selectedRefund.stripeChargeId || "N/A"}
                    </p>
                    <p>
                      <span className="text-gray-500">Customer ID:</span>{" "}
                      {selectedRefund.customerId}
                    </p>
                  </div>
                </div>

                {/* Reason */}
                <div className="border rounded-lg p-4">
                  <h3 className="font-medium text-gray-900 mb-3 flex items-center gap-2">
                    <FileText className="w-4 h-4" /> Reason
                  </h3>
                  <div className="space-y-2 text-sm">
                    <p>
                      <span className="text-gray-500">Refund Reason:</span>{" "}
                      {getReasonLabel(selectedRefund.reason)}
                    </p>
                    {selectedRefund.customerReason && (
                      <p>
                        <span className="text-gray-500">Customer Notes:</span>{" "}
                        {selectedRefund.customerReason}
                      </p>
                    )}
                    {selectedRefund.staffNotes && (
                      <p>
                        <span className="text-gray-500">Staff Notes:</span>{" "}
                        {selectedRefund.staffNotes}
                      </p>
                    )}
                    {selectedRefund.failureReason && (
                      <p className="text-red-600">
                        <span className="text-gray-500">Failure Reason:</span>{" "}
                        {selectedRefund.failureReason}
                      </p>
                    )}
                  </div>
                </div>

                {/* Dates */}
                <div className="border rounded-lg p-4">
                  <h3 className="font-medium text-gray-900 mb-3 flex items-center gap-2">
                    <Clock className="w-4 h-4" /> Timeline
                  </h3>
                  <div className="space-y-2 text-sm">
                    <p>
                      <span className="text-gray-500">Created:</span>{" "}
                      {formatDate(selectedRefund.createdAt)}
                    </p>
                    {selectedRefund.processedAt && (
                      <p>
                        <span className="text-gray-500">Processed:</span>{" "}
                        {formatDate(selectedRefund.processedAt)}
                      </p>
                    )}
                    {selectedRefund.staffId && (
                      <p>
                        <span className="text-gray-500">Processed by:</span>{" "}
                        {selectedRefund.staffId}
                      </p>
                    )}
                  </div>
                </div>

                {/* Actions */}
                {selectedRefund.status === "pending" && canProcessRefunds && (
                  <div className="flex justify-end pt-4 border-t">
                    <button
                      onClick={() => handleCancelRefund(selectedRefund.id)}
                      className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
                    >
                      <Ban className="w-4 h-4" />
                      Cancel Refund
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Create Refund Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg max-w-xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6">
              <div className="flex justify-between items-start mb-6">
                <div>
                  <h2 className="text-xl font-bold text-gray-900">
                    Process New Refund
                  </h2>
                  <p className="text-sm text-gray-500">
                    Create a refund for a customer payment
                  </p>
                </div>
                <button
                  onClick={() => {
                    setShowCreateModal(false);
                    resetCreateForm();
                  }}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <X className="w-6 h-6" />
                </button>
              </div>

              <form onSubmit={handleCreateRefund} className="space-y-4">
                {/* Customer ID */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Stripe Customer ID *
                  </label>
                  <input
                    type="text"
                    value={createForm.customerId}
                    onChange={(e) => {
                      setCreateForm({
                        ...createForm,
                        customerId: e.target.value,
                      });
                      if (e.target.value.startsWith("cus_")) {
                        fetchRefundablePayments(e.target.value);
                      }
                    }}
                    placeholder="cus_xxx"
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-primary focus:border-transparent"
                    required
                  />
                </div>

                {/* Refundable Payments */}
                {loadingPayments && (
                  <div className="flex items-center gap-2 text-gray-500">
                    <RefreshCw className="w-4 h-4 animate-spin" />
                    Loading payments...
                  </div>
                )}

                {refundablePayments.length > 0 && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Select Payment to Refund
                    </label>
                    <select
                      value={createForm.paymentIntentId}
                      onChange={(e) =>
                        setCreateForm({
                          ...createForm,
                          paymentIntentId: e.target.value,
                        })
                      }
                      className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-primary focus:border-transparent"
                    >
                      <option value="">Select a payment...</option>
                      {refundablePayments.map((payment) => (
                        <option
                          key={payment.paymentIntentId}
                          value={payment.paymentIntentId}
                        >
                          {payment.currency.toUpperCase()}{" "}
                          {payment.amountRefundableFormatted} refundable (
                          {new Date(payment.created).toLocaleDateString()})
                        </option>
                      ))}
                    </select>
                  </div>
                )}

                {/* Manual Payment Intent ID */}
                {refundablePayments.length === 0 &&
                  !loadingPayments &&
                  createForm.customerId && (
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Payment Intent ID *
                      </label>
                      <input
                        type="text"
                        value={createForm.paymentIntentId}
                        onChange={(e) =>
                          setCreateForm({
                            ...createForm,
                            paymentIntentId: e.target.value,
                          })
                        }
                        placeholder="pi_xxx"
                        className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-primary focus:border-transparent"
                      />
                    </div>
                  )}

                {/* Partial Refund */}
                <div className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    id="isPartial"
                    checked={createForm.isPartial}
                    onChange={(e) =>
                      setCreateForm({
                        ...createForm,
                        isPartial: e.target.checked,
                      })
                    }
                    className="rounded border-gray-300 text-brand-primary focus:ring-brand-primary"
                  />
                  <label htmlFor="isPartial" className="text-sm text-gray-700">
                    Partial refund
                  </label>
                </div>

                {createForm.isPartial && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Refund Amount (in currency units, e.g., 50 for $50)
                    </label>
                    <input
                      type="number"
                      value={createForm.amount}
                      onChange={(e) =>
                        setCreateForm({ ...createForm, amount: e.target.value })
                      }
                      placeholder="50.00"
                      step="0.01"
                      min="0.01"
                      className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-primary focus:border-transparent"
                    />
                  </div>
                )}

                {/* Reason */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Refund Reason *
                  </label>
                  <select
                    value={createForm.reason}
                    onChange={(e) =>
                      setCreateForm({
                        ...createForm,
                        reason: e.target.value as
                          | "requested_by_customer"
                          | "duplicate"
                          | "fraudulent",
                      })
                    }
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-primary focus:border-transparent"
                    required
                  >
                    <option value="requested_by_customer">
                      Customer Request
                    </option>
                    <option value="duplicate">Duplicate Charge</option>
                    <option value="fraudulent">Fraudulent</option>
                  </select>
                </div>

                {/* Customer Reason */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Customer&apos;s Reason (optional)
                  </label>
                  <textarea
                    value={createForm.customerReason}
                    onChange={(e) =>
                      setCreateForm({
                        ...createForm,
                        customerReason: e.target.value,
                      })
                    }
                    placeholder="What the customer told us..."
                    rows={2}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-primary focus:border-transparent"
                  />
                </div>

                {/* Staff Notes */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Staff Notes (optional)
                  </label>
                  <textarea
                    value={createForm.staffNotes}
                    onChange={(e) =>
                      setCreateForm({
                        ...createForm,
                        staffNotes: e.target.value,
                      })
                    }
                    placeholder="Internal notes about this refund..."
                    rows={2}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-primary focus:border-transparent"
                  />
                </div>

                {/* Submit */}
                <div className="flex justify-end gap-3 pt-4 border-t">
                  <button
                    type="button"
                    onClick={() => {
                      setShowCreateModal(false);
                      resetCreateForm();
                    }}
                    className="px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    disabled={
                      creating ||
                      !createForm.customerId ||
                      !createForm.paymentIntentId
                    }
                    className="flex items-center gap-2 px-4 py-2 bg-brand-primary text-white rounded-lg hover:bg-brand-primary/90 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {creating ? (
                      <>
                        <RefreshCw className="w-4 h-4 animate-spin" />
                        Processing...
                      </>
                    ) : (
                      <>
                        <DollarSign className="w-4 h-4" />
                        Process Refund
                      </>
                    )}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
