import React, { useState, useEffect } from "react";
import {
  Plus,
  TrendUp,
  Calendar,
  Percent,
  CheckCircle,
  Clock,
  CurrencyDollar,
  ArrowRight,
  Target,
  Upload,
  X,
} from "@phosphor-icons/react";
import axios from "axios";
import useAuthStore from "../store/authStore";

export default function ProfitSweepManagement() {
  const { user } = useAuthStore();
  const [sweeps, setSweeps] = useState([]);
  const [rules, setRules] = useState([]);
  const [availableMonths, setAvailableMonths] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [showReceiptModal, setShowReceiptModal] = useState(false);
  const [selectedSweep, setSelectedSweep] = useState(null);
  const [receiptFile, setReceiptFile] = useState(null);
  const [activeTab, setActiveTab] = useState("transactions");
  const [viewMode, setViewMode] = useState("all"); // 'all', 'date_range'
  const [dateRange, setDateRange] = useState({ from: "", to: "" });

  const [formData, setFormData] = useState({
    rule_id: "",
    year_month: "",
    to_company_id: "",
    super_admin_bank_account_id: "",
    notes: "",
  });
  const [companies, setCompanies] = useState([]);
  const [superAdminBankAccounts, setSuperAdminBankAccounts] = useState([]);
  const [showRuleModal, setShowRuleModal] = useState(false);
  const [ruleForm, setRuleForm] = useState({
    subsidiary_id: "",
    parent_company_id: "",
    sweep_percentage: "",
    frequency: "monthly",
  });
  const [ruleSaving, setRuleSaving] = useState(false);
  const [selectedCompanyId, setSelectedCompanyId] = useState("");

  // No longer rely on company.is_holding_company in frontend logic.
  const isSuperAdmin =
    user?.roles?.some((r) => r.name === "Super Admin") ?? false;
  const canCreateRule = isSuperAdmin; // Super Admins may create allocation rules

  // Set initial company selection - only run once when component loads
  useEffect(() => {
    if (isSuperAdmin && companies.length > 0 && !selectedCompanyId) {
      // Only set default if no company is already selected
      setSelectedCompanyId(companies[0]?.id || "");
    } else if (!isSuperAdmin && user?.company_id) {
      setSelectedCompanyId(user.company_id);
    }
  }, [companies.length, isSuperAdmin, user?.company_id, selectedCompanyId]);

  useEffect(() => {
    fetchData();
  }, [activeTab, viewMode, dateRange, selectedCompanyId]); // selectedCompanyId triggers re-fetch

  const fetchData = async () => {
    try {
      setLoading(true);
      // Clear previous data to prevent mixing when switching companies
      setSweeps([]);
      setRules([]);
      setAvailableMonths([]);

      const [
        sweepsRes,
        rulesRes,
        compRes,
        monthsRes,
        invoicesRes,
        bankAccountsRes,
      ] = await Promise.all([
        axios.get("/api/profit-sweeps", {
          params:
            viewMode === "date_range"
              ? {
                  from_date: dateRange.from,
                  to_date: dateRange.to,
                }
              : {},
        }),
        axios.get("/api/profit-sweep-rules"),
        axios.get("/api/companies?per_page=1000&all=1"),
        axios.get("/api/profit-sweeps/available-months", {
          params: selectedCompanyId ? { company_id: selectedCompanyId } : {},
        }),
        axios
          .get("/api/invoices/profit-allocation", {
            params: selectedCompanyId ? { company_id: selectedCompanyId } : {},
          })
          .catch(() => ({ data: { data: [] } })),
        axios
          .get("/api/super-admin-bank-accounts/list")
          .catch(() => ({ data: { data: [] } })),
      ]);
      const sweepsData = sweepsRes.data.data || [];
      setRules(rulesRes.data.data || []);
      setAvailableMonths(monthsRes.data.data || []);
      const compData = compRes.data.data || compRes.data || [];
      setCompanies(Array.isArray(compData) ? compData : compData.data || []);
      setSuperAdminBankAccounts(bankAccountsRes.data.data || []);

      console.log("Profit allocation invoices response:", invoicesRes.data);

      // Combine sweeps with all profit allocation invoices (including paid)
      const allocationInvoices = (invoicesRes.data.data || []).map((inv) => ({
        id: inv.id,
        year_month: inv.allocation_month,
        source_company: {
          id: inv.company_id,
          name: inv.company?.name || "Unknown",
        },
        target_company: null,
        rule: null,
        amount: inv.total_amount,
        sweep_percentage: inv.sweep_percentage || 0,
        sweep_date: inv.invoice_date,
        month_revenue: inv.month_revenue || 0,
        month_expenses: inv.month_expenses || 0,
        month_net_profit: inv.month_net_profit || 0,
        is_no_profit_month: (inv.month_net_profit || 0) <= 0,
        status: inv.status === "paid" ? "processed" : "pending",
        notes: `Invoice: ${inv.invoice_number}`,
        is_invoice: true,
        invoice_id: inv.id,
      }));

      console.log("Allocation invoices mapped:", allocationInvoices);
      console.log("Setting sweeps with allocation invoices:", [
        ...allocationInvoices,
        ...sweepsData,
      ]);

      setSweeps([...allocationInvoices, ...sweepsData]);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmitSweep = async (e) => {
    e.preventDefault();
    try {
      await axios.post("/api/profit-sweeps/execute", {
        ...formData,
        company_id: selectedCompanyId,
      });
      setShowModal(false);
      resetForm();
      fetchData();
      alert("Profit sweep executed successfully!");
    } catch (error) {
      console.error("Error submitting sweep:", error);
      alert(error.response?.data?.message || "Error submitting profit sweep");
    }
  };

  const resetForm = () => {
    setFormData({
      rule_id: "",
      year_month: "",
      to_company_id: "",
      super_admin_bank_account_id: "",
      notes: "",
    });
  };

  const selectedRule = rules.find(
    (r) => String(r.id) === String(formData.rule_id),
  );
  const selectedMonth = availableMonths.find(
    (m) => m.year_month === formData.year_month,
  );
  const netProfit = selectedMonth ? selectedMonth.net_profit : 0;
  const calcAmount =
    selectedRule && netProfit > 0
      ? Math.round(netProfit * (selectedRule.sweep_percentage / 100) * 100) /
        100
      : 0;

  const openReceiptModal = (sweep) => {
    setSelectedSweep(sweep);
    setReceiptFile(null);
    setShowReceiptModal(true);
  };

  const handleCreateRule = async (e) => {
    e.preventDefault();
    setRuleSaving(true);
    try {
      await axios.post("/api/profit-sweep-rules", ruleForm);
      setShowRuleModal(false);
      setRuleForm({
        subsidiary_id: "",
        parent_company_id: "",
        sweep_percentage: "",
        frequency: "monthly",
      });
      fetchData();
      alert("Allocation rule saved successfully!");
    } catch (err) {
      alert(err.response?.data?.message || "Failed to save rule");
    } finally {
      setRuleSaving(false);
    }
  };

  const submitReceipt = async (e) => {
    e.preventDefault();
    if (!receiptFile) return alert("Please select a receipt file");
    const fd = new FormData();
    fd.append("receipt", receiptFile);
    try {
      await axios.post(`/api/profit-sweeps/${selectedSweep.id}/receipt`, fd, {
        headers: { "Content-Type": "multipart/form-data" },
      });
      alert("Receipt uploaded successfully");
      setShowReceiptModal(false);
      fetchData();
    } catch (e) {
      alert(e.response?.data?.message || "Upload failed");
    }
  };

  const safeDate = (val) => {
    if (!val) return "—";
    const d = new Date(val);
    if (isNaN(d.getTime())) return "—";
    return d.toLocaleDateString();
  };

  const getFrequencyColor = (frequency) => {
    const colors = {
      monthly: "bg-primary-100 text-primary-700 border-primary-200",
      quarterly: "bg-purple-100 text-purple-700 border-purple-200",
      annually: "bg-green-100 text-green-700 border-green-200",
    };
    return colors[frequency] || "bg-gray-100 text-gray-700 border-gray-200";
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-green-50 p-6">
      {/* Header */}
      <div className="mb-8">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2 flex items-center gap-3">
              <TrendUp size={36} weight="duotone" className="text-green-600" />
              Profit Allocation Management
            </h1>
            <p className="text-gray-600">
              {canCreateRule
                ? "Monitor profit distributions from subsidiary companies"
                : "Submit profit percentages to Sarkin Mota Group"}
            </p>
          </div>
          <div className="flex gap-3">
            {canCreateRule && (
              <button
                onClick={() => setShowRuleModal(true)}
                className="flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-purple-600 to-indigo-600 text-white rounded-xl hover:opacity-90 transition-all shadow-lg text-sm font-semibold"
              >
                <Plus size={18} weight="bold" /> Set Allocation Rule
              </button>
            )}
            {isSuperAdmin && (
              <button
                onClick={() => setShowModal(true)}
                className="flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-green-600 to-emerald-600 text-white rounded-xl hover:opacity-90 transition-all shadow-lg text-sm font-semibold"
              >
                <Plus size={18} weight="bold" /> Execute Profit Sweep
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div className="bg-gradient-to-br from-green-500 to-green-600 rounded-2xl shadow-xl p-6 text-white">
          <div className="flex items-center justify-between mb-4">
            <CurrencyDollar size={32} weight="duotone" className="opacity-80" />
          </div>
          <h3 className="text-sm font-medium opacity-90 mb-1">Total Revenue</h3>
          <p className="text-3xl font-bold">
            ₦
            {Number(
              availableMonths.reduce(
                (sum, m) => sum + Number(m.revenue || 0),
                0,
              ),
            ).toLocaleString()}
          </p>
        </div>

        <div className="bg-gradient-to-br from-red-500 to-red-600 rounded-2xl shadow-xl p-6 text-white">
          <div className="flex items-center justify-between mb-4">
            <Clock size={32} weight="duotone" className="opacity-80" />
          </div>
          <h3 className="text-sm font-medium opacity-90 mb-1">
            Total Expenses
          </h3>
          <p className="text-3xl font-bold">
            ₦
            {Number(
              availableMonths.reduce(
                (sum, m) => sum + Number(m.expenses || 0),
                0,
              ),
            ).toLocaleString()}
          </p>
        </div>

        <div className="bg-gradient-to-br from-primary-500 to-primary-600 rounded-2xl shadow-xl p-6 text-white">
          <div className="flex items-center justify-between mb-4">
            <Target size={32} weight="duotone" className="opacity-80" />
          </div>
          <h3 className="text-sm font-medium opacity-90 mb-1">
            Total Net Profit
          </h3>
          <p className="text-3xl font-bold">
            ₦
            {Number(
              availableMonths.reduce(
                (sum, m) => sum + Number(m.net_profit || 0),
                0,
              ),
            ).toLocaleString()}
          </p>
        </div>

        <div className="bg-gradient-to-br from-purple-500 to-purple-600 rounded-2xl shadow-xl p-6 text-white">
          <div className="flex items-center justify-between mb-4">
            <CheckCircle size={32} weight="duotone" className="opacity-80" />
          </div>
          <h3 className="text-sm font-medium opacity-90 mb-1">
            Total Allocated
          </h3>
          <p className="text-3xl font-bold">
            ₦
            {Number(
              sweeps.reduce((sum, s) => sum + Number(s.amount || 0), 0),
            ).toLocaleString()}
          </p>
        </div>
      </div>

      {/* View Mode Toggle */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-6">
        <div className="flex items-center justify-between">
          <div className="flex gap-2">
            <button
              onClick={() => setViewMode("all")}
              className={`px-4 py-2 rounded-lg font-medium transition-all ${
                viewMode === "all"
                  ? "bg-green-600 text-white shadow-md"
                  : "text-gray-600 hover:bg-gray-100"
              }`}
            >
              All Time
            </button>
            <button
              onClick={() => setViewMode("date_range")}
              className={`px-4 py-2 rounded-lg font-medium transition-all ${
                viewMode === "date_range"
                  ? "bg-green-600 text-white shadow-md"
                  : "text-gray-600 hover:bg-gray-100"
              }`}
            >
              Date Range
            </button>
          </div>
          {isSuperAdmin && companies.length > 0 && (
            <div className="flex items-center gap-2">
              <label className="text-sm font-medium text-gray-600">
                Company:
              </label>
              <select
                value={selectedCompanyId}
                onChange={(e) => setSelectedCompanyId(e.target.value)}
                className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
              >
                {companies.map((c) => (
                  <option key={c.id} value={c.id}>
                    {c.name}
                  </option>
                ))}
              </select>
            </div>
          )}
          {viewMode === "date_range" && (
            <div className="flex gap-2">
              <input
                type="date"
                value={dateRange.from}
                onChange={(e) =>
                  setDateRange({ ...dateRange, from: e.target.value })
                }
                className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
              />
              <input
                type="date"
                value={dateRange.to}
                onChange={(e) =>
                  setDateRange({ ...dateRange, to: e.target.value })
                }
                className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
              />
            </div>
          )}
        </div>
      </div>

      {/* Tabs */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-2 mb-6">
        <div className="flex gap-2">
          <button
            onClick={() => setActiveTab("transactions")}
            className={`px-6 py-2 rounded-lg font-medium transition-all ${
              activeTab === "transactions"
                ? "bg-green-600 text-white shadow-md"
                : "text-gray-600 hover:bg-gray-100"
            }`}
          >
            Transactions
          </button>
          <button
            onClick={() => setActiveTab("rules")}
            className={`px-6 py-2 rounded-lg font-medium transition-all ${
              activeTab === "rules"
                ? "bg-green-600 text-white shadow-md"
                : "text-gray-600 hover:bg-gray-100"
            }`}
          >
            Allocation Rules
          </button>
        </div>
      </div>

      {/* Content */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-green-600"></div>
        </div>
      ) : activeTab === "transactions" ? (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {sweeps.map((sweep) => (
            <div
              key={sweep.id}
              className="bg-white rounded-2xl shadow-lg border border-gray-100 p-6 hover:shadow-xl transition-all"
            >
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-green-500 to-primary-600 flex items-center justify-center text-white font-bold text-lg">
                    {sweep.source_company?.name?.charAt(0)}
                  </div>
                  <div>
                    <h3 className="font-bold text-lg text-gray-900">
                      {sweep.source_company?.name}
                    </h3>
                    <p className="text-sm text-gray-500">
                      →{" "}
                      {sweep.is_super_admin_recipient
                        ? "Super Admin"
                        : sweep.target_company?.name}
                    </p>
                    {sweep.year_month && (
                      <p className="text-xs text-gray-400 mt-1">
                        {sweep.year_month}
                      </p>
                    )}
                  </div>
                </div>
                <span
                  className={`px-3 py-1 rounded-lg text-xs font-semibold border ${
                    sweep.is_no_profit_month
                      ? "bg-yellow-100 text-yellow-700 border-yellow-200"
                      : ["completed", "processed", "paid"].includes(
                            sweep.status,
                          )
                        ? "bg-green-100 text-green-700 border-green-200"
                        : sweep.status === "pending"
                          ? "bg-yellow-100 text-yellow-700 border-yellow-200"
                          : sweep.status === "failed"
                            ? "bg-red-100 text-red-700 border-red-200"
                            : "bg-gray-100 text-gray-700 border-gray-200"
                  }`}
                >
                  {sweep.is_no_profit_month
                    ? "No Profit"
                    : sweep.status === "processed"
                      ? "paid"
                      : sweep.status}
                </span>
              </div>

              {!sweep.is_no_profit_month && (
                <div className="grid grid-cols-2 gap-4 mb-4">
                  <div className="bg-green-50 rounded-xl p-4">
                    <div className="flex items-center gap-2 mb-2">
                      <CurrencyDollar
                        size={20}
                        className="text-green-600"
                        weight="duotone"
                      />
                      <span className="text-xs font-medium text-gray-600">
                        Allocated Amount
                      </span>
                    </div>
                    <p className="text-2xl font-bold text-gray-900">
                      ₦{Number(sweep.amount || 0).toLocaleString()}
                    </p>
                  </div>

                  <div className="bg-purple-50 rounded-xl p-4">
                    <div className="flex items-center gap-2 mb-2">
                      <Percent
                        size={20}
                        className="text-purple-600"
                        weight="duotone"
                      />
                      <span className="text-xs font-medium text-gray-600">
                        Percentage
                      </span>
                    </div>
                    <p className="text-2xl font-bold text-gray-900">
                      {sweep.sweep_percentage}%
                    </p>
                  </div>
                </div>
              )}

              {/* Monthly Financial Breakdown */}
              {(sweep.month_revenue !== undefined ||
                sweep.month_expenses !== undefined) && (
                <div className="bg-gray-50 rounded-xl p-4 mb-4 space-y-2">
                  <h4 className="text-xs font-semibold text-gray-700 uppercase tracking-wide">
                    Monthly Breakdown
                  </h4>
                  <div className="grid grid-cols-3 gap-2">
                    <div className="text-center">
                      <p className="text-xs text-gray-500">Revenue</p>
                      <p className="text-sm font-bold text-green-700">
                        ₦{Number(sweep.month_revenue || 0).toLocaleString()}
                      </p>
                    </div>
                    <div className="text-center">
                      <p className="text-xs text-gray-500">Expenses</p>
                      <p className="text-sm font-bold text-red-700">
                        ₦{Number(sweep.month_expenses || 0).toLocaleString()}
                      </p>
                    </div>
                    <div className="text-center">
                      <p className="text-xs text-gray-500">Net Profit</p>
                      <p className="text-sm font-bold text-primary-700">
                        ₦{Number(sweep.month_net_profit || 0).toLocaleString()}
                      </p>
                    </div>
                  </div>
                </div>
              )}

              <div className="flex items-center justify-between text-sm mb-4">
                <div className="flex items-center gap-2">
                  <Calendar size={16} className="text-gray-500" />
                  <span className="text-gray-600">
                    {safeDate(sweep.sweep_date)}
                  </span>
                </div>
              </div>

              {sweep.notes && (
                <div className="p-3 bg-gray-50 rounded-lg mb-4">
                  <p className="text-xs text-gray-600">{sweep.notes}</p>
                </div>
              )}
              <div className="mt-4 flex gap-2">
                {!["processed", "completed", "paid"].includes(sweep.status) &&
                  !sweep.is_no_profit_month && (
                    <button
                      onClick={() => openReceiptModal(sweep)}
                      className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-green-600 text-white rounded-xl hover:bg-green-700 transition-colors text-sm font-semibold"
                    >
                      <Upload size={16} weight="bold" /> Upload Receipt
                    </button>
                  )}
                {sweep.receipt_path && (
                  <a
                    href={`/storage/${sweep.receipt_path}`}
                    target="_blank"
                    rel="noreferrer"
                    className="px-4 py-2 bg-gray-100 text-gray-700 rounded-xl hover:bg-gray-200 transition-colors text-sm font-semibold"
                  >
                    View Receipt
                  </a>
                )}
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {rules.map((rule) => (
            <div
              key={rule.id}
              className="bg-white rounded-2xl shadow-lg border border-gray-100 p-6"
            >
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-green-500 to-primary-600 flex items-center justify-center text-white">
                    <Target size={20} weight="duotone" />
                  </div>
                  <div>
                    <h3 className="font-bold text-gray-900">
                      {rule.rule_name}
                    </h3>
                    <p className="text-xs text-gray-500">
                      {rule.source_company?.name}
                    </p>
                  </div>
                </div>
                <span
                  className={`px-2 py-1 rounded-md text-xs font-semibold ${
                    rule.is_active
                      ? "bg-green-100 text-green-700"
                      : "bg-gray-100 text-gray-600"
                  }`}
                >
                  {rule.is_active ? "Active" : "Inactive"}
                </span>
              </div>

              <div className="space-y-3 mb-4">
                <div className="flex items-center justify-between p-3 bg-purple-50 rounded-lg">
                  <span className="text-sm text-gray-600">
                    Allocation Percentage
                  </span>
                  <span className="font-bold text-purple-700">
                    {rule.sweep_percentage}%
                  </span>
                </div>

                <div className="flex items-center justify-between p-3 bg-primary-50 rounded-lg">
                  <span className="text-sm text-gray-600">Frequency</span>
                  <span className="font-bold text-primary-700 capitalize">
                    {rule.frequency}
                  </span>
                </div>

                {rule.minimum_amount > 0 && (
                  <div className="flex items-center justify-between p-3 bg-green-50 rounded-lg">
                    <span className="text-sm text-gray-600">Minimum</span>
                    <span className="font-bold text-green-700">
                      ₦{Number(rule.minimum_amount).toLocaleString()}
                    </span>
                  </div>
                )}
              </div>

              <div className="text-xs text-gray-500">
                Last executed:{" "}
                {safeDate(rule.last_executed_at) !== "—"
                  ? safeDate(rule.last_executed_at)
                  : "Never"}
              </div>
            </div>
          ))}
          {canCreateRule && rules.length === 0 && (
            <div className="col-span-3 text-center py-12 text-gray-400">
              <Target size={40} className="mx-auto mb-3 opacity-30" />
              <p className="font-medium">No allocation rules yet</p>
              <p className="text-sm mt-1">
                Click "Set Allocation Rule" to create one per company
              </p>
            </div>
          )}
        </div>
      )}

      {/* Create Rule Modal (Super Admin) */}
      {showRuleModal && (
        <div
          className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
          onClick={() => setShowRuleModal(false)}
        >
          <div
            className="bg-white rounded-2xl shadow-2xl w-full max-w-lg"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="bg-gradient-to-r from-purple-600 to-indigo-600 text-white px-6 py-4 rounded-t-2xl flex justify-between items-center">
              <div>
                <h2 className="text-xl font-bold">Set Allocation Rule</h2>
                <p className="text-xs opacity-80 mt-0.5">
                  Define how much % of a company's net profit is swept
                </p>
              </div>
              <button
                onClick={() => setShowRuleModal(false)}
                className="hover:bg-white/20 rounded-lg p-1"
              >
                <X size={20} weight="bold" />
              </button>
            </div>
            <form onSubmit={handleCreateRule} className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1">
                  Company (Subsidiary) *
                </label>
                <select
                  required
                  value={ruleForm.subsidiary_id}
                  onChange={(e) =>
                    setRuleForm((p) => ({
                      ...p,
                      subsidiary_id: e.target.value,
                    }))
                  }
                  className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                >
                  <option value="">— Select company —</option>
                  {companies.map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.name}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1">
                  Receiving Company (Parent / Holding)
                </label>
                <select
                  value={ruleForm.parent_company_id}
                  onChange={(e) =>
                    setRuleForm((p) => ({
                      ...p,
                      parent_company_id: e.target.value,
                    }))
                  }
                  className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                >
                  <option value="">— Auto-detect holding company —</option>
                  {companies.map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.name} {c.is_holding_company ? "(Holding)" : ""}
                    </option>
                  ))}
                </select>
                <p className="text-xs text-gray-400 mt-1">
                  Leave blank to auto-select the holding company. Select
                  manually if no company is marked as holding.
                </p>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">
                    Sweep % of Net Profit *
                  </label>
                  <input
                    type="number"
                    required
                    min="0.01"
                    max="100"
                    step="any"
                    value={ruleForm.sweep_percentage}
                    onChange={(e) =>
                      setRuleForm((p) => ({
                        ...p,
                        sweep_percentage: e.target.value,
                      }))
                    }
                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                    placeholder="e.g. 20"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">
                    Frequency *
                  </label>
                  <select
                    value={ruleForm.frequency}
                    onChange={(e) =>
                      setRuleForm((p) => ({ ...p, frequency: e.target.value }))
                    }
                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                  >
                    <option value="monthly">Monthly</option>
                    <option value="quarterly">Quarterly</option>
                    <option value="annual">Annual</option>
                  </select>
                </div>
              </div>
              {ruleForm.sweep_percentage > 0 && (
                <div className="bg-purple-50 border border-purple-200 rounded-xl p-4">
                  <p className="text-sm font-semibold text-purple-800">
                    {ruleForm.sweep_percentage}% of this company's net profit
                    will be swept to Sarkin Mota Group on a{" "}
                    <span className="capitalize">{ruleForm.frequency}</span>{" "}
                    basis.
                  </p>
                  <p className="text-xs text-purple-600 mt-1">
                    The naira amount will be calculated automatically at the
                    time of each sweep.
                  </p>
                </div>
              )}
              <div className="flex gap-3 pt-2">
                <button
                  type="button"
                  onClick={() => setShowRuleModal(false)}
                  className="flex-1 px-4 py-3 bg-gray-100 text-gray-700 rounded-xl font-semibold"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={ruleSaving}
                  className="flex-1 px-4 py-3 bg-gradient-to-r from-purple-600 to-indigo-600 text-white rounded-xl font-semibold hover:opacity-90"
                >
                  {ruleSaving ? "Saving..." : "Save Rule"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Receipt Upload Modal */}
      {showReceiptModal && selectedSweep && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
          onClick={() => setShowReceiptModal(false)}
        >
          <div
            className="bg-white rounded-2xl shadow-2xl w-full max-w-md"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="bg-gradient-to-r from-green-600 to-emerald-600 text-white px-6 py-4 rounded-t-2xl flex justify-between items-center">
              <h2 className="text-xl font-bold">Upload Receipt</h2>
              <button
                onClick={() => setShowReceiptModal(false)}
                className="hover:bg-white/20 rounded-lg p-1"
              >
                <X size={20} weight="bold" />
              </button>
            </div>
            <form onSubmit={submitReceipt} className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Allocation
                </label>
                <p className="text-gray-900 font-medium">
                  {selectedSweep.source_company?.name} →{" "}
                  {selectedSweep.is_super_admin_recipient
                    ? "Super Admin"
                    : selectedSweep.target_company?.name}
                </p>
                <p className="text-sm text-gray-500">
                  Amount: ₦{Number(selectedSweep.amount || 0).toLocaleString()}
                </p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Receipt File
                </label>
                <input
                  type="file"
                  accept=".pdf,.jpg,.jpeg,.png"
                  required
                  onChange={(e) => setReceiptFile(e.target.files[0])}
                  className="w-full text-sm"
                />
                <p className="text-xs text-gray-500 mt-1">
                  PDF, JPG, PNG up to 2MB
                </p>
              </div>
              <div className="flex gap-3 pt-2">
                <button
                  type="button"
                  onClick={() => setShowReceiptModal(false)}
                  className="flex-1 px-4 py-3 bg-gray-100 text-gray-700 rounded-xl font-semibold hover:bg-gray-200 transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 px-4 py-3 bg-green-600 text-white rounded-xl font-semibold hover:bg-green-700 transition-colors"
                >
                  Upload Receipt
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Execute Profit Sweep Modal */}
      {showModal && (
        <div
          className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
          onClick={() => setShowModal(false)}
        >
          <div
            className="bg-white rounded-2xl shadow-2xl w-full max-w-lg"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="bg-gradient-to-r from-green-600 to-emerald-600 text-white px-6 py-4 rounded-t-2xl flex justify-between items-center">
              <div>
                <h2 className="text-xl font-bold">Execute Profit Sweep</h2>
                <p className="text-xs opacity-80 mt-0.5">
                  Allocate profit to Super Admin bank account
                </p>
              </div>
              <button
                onClick={() => setShowModal(false)}
                className="hover:bg-white/20 rounded-lg p-1"
              >
                <X size={20} weight="bold" />
              </button>
            </div>
            <form onSubmit={handleSubmitSweep} className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1">
                  Allocation Rule *
                </label>
                <select
                  required
                  value={formData.rule_id}
                  onChange={(e) =>
                    setFormData((p) => ({ ...p, rule_id: e.target.value }))
                  }
                  className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-green-500 focus:border-transparent"
                >
                  <option value="">— Select rule —</option>
                  {rules.map((r) => (
                    <option key={r.id} value={r.id}>
                      {r.rule_name} ({r.sweep_percentage}%)
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1">
                  Month *
                </label>
                <select
                  required
                  value={formData.year_month}
                  onChange={(e) =>
                    setFormData((p) => ({ ...p, year_month: e.target.value }))
                  }
                  className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-green-500 focus:border-transparent"
                >
                  <option value="">— Select month —</option>
                  {availableMonths.map((m) => (
                    <option key={m.year_month} value={m.year_month}>
                      {m.year_month} (Net Profit: ₦
                      {Number(m.net_profit || 0).toLocaleString()})
                    </option>
                  ))}
                </select>
              </div>
              {isSuperAdmin && (
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">
                    Select Super Admin Bank Account
                  </label>
                  <select
                    value={formData.super_admin_bank_account_id}
                    onChange={(e) =>
                      setFormData((p) => ({
                        ...p,
                        super_admin_bank_account_id: e.target.value,
                      }))
                    }
                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-green-500 focus:border-transparent"
                  >
                    <option value="">— Select bank account —</option>
                    {superAdminBankAccounts.map((ba) => (
                      <option key={ba.id} value={ba.id}>
                        {ba.bank_name} - {ba.account_number} ({ba.account_name})
                      </option>
                    ))}
                  </select>
                </div>
              )}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1">
                  Notes
                </label>
                <textarea
                  value={formData.notes}
                  onChange={(e) =>
                    setFormData((p) => ({ ...p, notes: e.target.value }))
                  }
                  className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-green-500 focus:border-transparent"
                  rows="3"
                  placeholder="Optional notes..."
                />
              </div>
              {selectedRule && selectedMonth && (
                <div className="bg-green-50 border border-green-200 rounded-xl p-4">
                  <p className="text-sm font-semibold text-green-800">
                    Calculated Amount: ₦{calcAmount.toLocaleString()}
                  </p>
                  <p className="text-xs text-green-600 mt-1">
                    {selectedRule.sweep_percentage}% of ₦
                    {Number(selectedMonth.net_profit || 0).toLocaleString()}{" "}
                    (Net Profit)
                  </p>
                </div>
              )}
              <div className="flex gap-3 pt-2">
                <button
                  type="button"
                  onClick={() => setShowModal(false)}
                  className="flex-1 px-4 py-3 bg-gray-100 text-gray-700 rounded-xl font-semibold"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 px-4 py-3 bg-gradient-to-r from-green-600 to-emerald-600 text-white rounded-xl font-semibold hover:opacity-90"
                >
                  Execute Sweep
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
