
import React, { useMemo, useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Download, Search, Building2, MapPin, DollarSign } from "lucide-react";
import PageHeader from "@/components/common/PageHeader";
import { Input } from "@/components/ui/input";

// Define regions - these map to the notes field or can be a new field
const REGIONS = [
  "Bay Area",
  "Southern California", 
  "Northern California",
  "National"
];

function fmtCurrency(v) {
  if (typeof v !== "number" || Number.isNaN(v)) return "—";
  return v.toLocaleString(undefined, { style: "currency", currency: "USD" });
}

function downloadCSV(rows, regionName, vendorName) {
  const headers = ["Role", "Category", "Employee Wage", "Markup %", "Vendor Fee %", "Client Rate"];
  const lines = [headers.join(",")];
  for (const r of rows) {
    const cells = [
      r.role_name,
      r.category,
      r.employee_wage,
      r.markup_percentage,
      r.vendor_fee_percentage,
      r.client_rate
    ];
    lines.push(cells.join(","));
  }
  const blob = new Blob([lines.join("\n")], { type: "text/csv;charset=utf-8;" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `${vendorName}_${regionName}_Rates_${new Date().toISOString().slice(0,10)}.csv`;
  a.click();
  URL.revokeObjectURL(url);
}

// NEW: Helper function to parse role name into position and region
const parseRoleName = (roleName) => {
  if (!roleName) return { position: '', region: '' };
  
  // Check if role name contains a hyphen separator
  if (roleName.includes(' - ')) {
    const parts = roleName.split(' - ');
    return {
      position: parts[0].trim(),
      region: parts[1].trim()
    };
  }
  
  // If no hyphen, return the whole name as position
  return {
    position: roleName,
    region: ''
  };
};

// ==================== VENDOR-ONLY COMPONENT ====================
function VendorCompanyPricebookView({ user, vendorName }) {
  const APPROVED_TAG = "__APPROVED__";
  
  const [clients, setClients] = useState(["Google", "Zoox", "Promotion"]);
  const [pricebook, setPricebook] = useState("Approved");
  const [search, setSearch] = useState("");
  const [activeRegion, setActiveRegion] = useState("All");
  const [activeCategory, setActiveCategory] = useState("All");
  const [editing, setEditing] = useState(null);
  const [toast, setToast] = useState(null);

  const { data: rates = [] } = useQuery({
    queryKey: ['vendor-rates-pricebook', vendorName],
    queryFn: async () => {
      const allRates = await base44.entities.VendorRate.list();
      // FOR DEMO: Show Legendary Event Staffing rates if no rates for current vendor
      const vendorRates = allRates.filter(r => r.vendor_name === vendorName && r.is_active);
      if (vendorRates.length === 0) {
        // Show demo data from Legendary Event Staffing
        return allRates.filter(r => r.vendor_name === "Legendary Event Staffing" && r.is_active);
      }
      return vendorRates;
    },
    initialData: [],
    enabled: !!vendorName,
  });

  const CATEGORIES = [
    "Kitchen and Culinary",
    "Event Staff",
    "Bartending",
    "Management",
    "Facilities",
    "Concessions",
    "Other"
  ];

  const scopedByBook = useMemo(() => {
    // Convert existing rates to pricebook format
    // For now, treat all as "Approved" pricebook
    return rates.map(r => ({
      ...r,
      client: APPROVED_TAG,
      region: r.notes?.includes("Bay Area") ? "Bay Area" : "LA", // Simplified for demo
      approvedCap: r.client_rate,
      proposedRate: r.client_rate,
      position: r.role_name,
      markupPct: r.markup_percentage,
      volDiscountPct: r.vendor_fee_percentage
    }));
  }, [rates]);

  const filtered = useMemo(() => {
    return scopedByBook.filter(r =>
      (activeRegion === "All" || parseRoleName(r.position).region === activeRegion) && // Updated region filter to use parsed region
      (activeCategory === "All" || r.category === activeCategory) &&
      (search.trim() === "" || parseRoleName(r.position).position.toLowerCase().includes(search.toLowerCase())) // Updated search to use parsed position
    );
  }, [scopedByBook, activeRegion, activeCategory, search]);

  const kpis = useMemo(() => {
    const rateValues = filtered.map(r => r.proposedRate);
    const avg = rateValues.length ? rateValues.reduce((a, b) => a + b, 0) / rateValues.length : 0;
    const min = rateValues.length ? Math.min(...rateValues) : 0;
    const max = rateValues.length ? Math.max(...rateValues) : 0;
    const total = filtered.length;
    return { avg, min, max, total };
  }, [filtered]);

  function exportCSV() {
    const headers = ["Pricebook", "Position", "Category", "Region", "ApprovedCap", "ProposedRate", "Markup%", "VolDiscount%"];
    const body = filtered.map(r => {
      const parsed = parseRoleName(r.position); // Parse role_name for export
      return [
        pricebook,
        parsed.position,
        r.category,
        parsed.region,
        r.approvedCap,
        r.proposedRate,
        r.markupPct,
        r.volDiscountPct
      ];
    });
    const csv = [headers, ...body]
      .map(row => row.map(v => (typeof v === "string" ? `"${v}"` : v)).join(","))
      .join("\n");
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `service-rates-${pricebook}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="min-h-screen bg-slate-50">
      {/* Header */}
      <header className="px-6 py-6 border-b bg-white sticky top-0 z-10">
        <div className="max-w-7xl mx-auto flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-semibold text-slate-900">
              <span className="bg-yellow-300 px-2 rounded">Service Rates</span> 2025–2028
            </h1>
            <p className="text-slate-500 mt-1">
              {rates.length > 0 && rates[0].vendor_name !== vendorName ? (
                <>Demo data from <strong>Legendary Event Staffing</strong> - View <strong>Approved Prices</strong></>
              ) : (
                <>{vendorName} - View <strong>Approved Prices</strong> and manage <strong>Company-specific pricebooks</strong></>
              )}
            </p>
          </div>
          <Button onClick={exportCSV} variant="outline" className="border-slate-300">
            <Download className="w-4 h-4 mr-2" />
            Export CSV
          </Button>
        </div>
      </header>

      {/* Pricebook Tabs */}
      <section className="max-w-7xl mx-auto px-6 mt-6">
        <div className="flex flex-wrap gap-2 items-center">
          {["Approved", ...clients].map(tab => (
            <button
              key={tab}
              onClick={() => setPricebook(tab)}
              className={`px-3 py-1.5 rounded-full text-sm border transition-all ${
                pricebook === tab
                  ? "bg-slate-900 text-white border-slate-900"
                  : "bg-white hover:bg-slate-50"
              }`}
            >
              {tab}
            </button>
          ))}
          <span className="text-slate-400 text-sm ml-2">Pricebook</span>
        </div>
      </section>

      {/* KPI Cards */}
      <section className="max-w-7xl mx-auto px-6 mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card className="border-slate-200">
          <CardContent className="p-5">
            <p className="text-slate-500 text-sm mb-1">Average Rate</p>
            <p className="text-2xl font-semibold">{fmtCurrency(kpis.avg)}</p>
            <p className="text-xs text-slate-400 mt-2">Based on current filters</p>
          </CardContent>
        </Card>
        <Card className="border-slate-200">
          <CardContent className="p-5">
            <p className="text-sm text-slate-500 mb-1">Total Positions</p>
            <p className="text-2xl font-semibold">{kpis.total}</p>
            <p className="text-xs text-slate-400 mt-2">
              {pricebook === "Approved" ? "Approved prices" : `${pricebook} pricebook`}
            </p>
          </CardContent>
        </Card>
        <Card className="border-slate-200">
          <CardContent className="p-5">
            <p className="text-sm text-slate-500 mb-1">Price Range</p>
            <p className="text-2xl font-semibold">
              {fmtCurrency(kpis.min)} – {fmtCurrency(kpis.max)}
            </p>
            <p className="text-xs text-slate-400 mt-2">Min – Max</p>
          </CardContent>
        </Card>
      </section>

      {/* Category Filters + Search */}
      <section className="max-w-7xl mx-auto px-6 mt-6">
        <div className="flex items-center flex-wrap gap-2">
          {["All", ...CATEGORIES].map(cat => (
            <button
              key={cat}
              onClick={() => setActiveCategory(cat)}
              className={`px-3 py-1.5 rounded-full text-sm border transition-all ${
                activeCategory === cat
                  ? "bg-slate-900 text-white border-slate-900"
                  : "bg-white hover:bg-slate-50"
              }`}
            >
              {cat}
            </button>
          ))}
          <div className="ml-auto w-full md:w-72">
            <Input
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Search positions…"
              className="w-full"
            />
          </div>
        </div>
      </section>

      {/* Table */}
      <section className="max-w-7xl mx-auto px-6 mt-4 mb-8">
        <div className="overflow-hidden rounded-2xl border bg-white">
          <table className="w-full text-left">
            <thead className="bg-slate-50">
              <tr className="text-slate-500 text-sm">
                <th className="px-4 py-3">Position</th>
                <th className="px-4 py-3">Category</th>
                <th className="px-4 py-3">Region</th>
                <th className="px-4 py-3">Employee Wage</th>
                <th className="px-4 py-3">Client Rate</th>
                <th className="px-4 py-3">Markup %</th>
                <th className="px-4 py-3">VA Fee %</th>
                <th className="px-4 py-3">Status</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((r, idx) => {
                const parsed = parseRoleName(r.position);
                
                return (
                  <tr key={r.id || idx} className="border-t hover:bg-slate-50/60">
                    <td className="px-4 py-3 font-medium">{parsed.position}</td>
                    <td className="px-4 py-3">
                      <Badge variant="outline" className="text-xs">{r.category}</Badge>
                    </td>
                    <td className="px-4 py-3">{parsed.region || '—'}</td>
                    <td className="px-4 py-3">{fmtCurrency(r.employee_wage)}</td>
                    <td className="px-4 py-3 font-semibold text-[#0A39DF]">{fmtCurrency(r.proposedRate)}</td>
                    <td className="px-4 py-3">{r.markupPct}%</td>
                    <td className="px-4 py-3">{r.volDiscountPct}%</td>
                    <td className="px-4 py-3">
                      <Badge className="bg-green-100 text-green-700">Approved</Badge>
                    </td>
                  </tr>
                );
              })}
              {filtered.length === 0 && (
                <tr>
                  <td className="px-4 py-8 text-center text-slate-500" colSpan={8}>
                    No results. Adjust filters or search.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </section>

      {/* Toast */}
      {toast && (
        <div className="fixed bottom-6 left-1/2 -translate-x-1/2 bg-slate-900 text-white text-sm px-4 py-2 rounded-xl shadow-lg z-50">
          {toast}
          <button className="ml-3 opacity-70 hover:opacity-100" onClick={() => setToast(null)}>✕</button>
        </div>
      )}
    </div>
  );
}

// ==================== ADMIN/PROCUREMENT VIEW (EXISTING) ====================
function AdminProcurementRatesView({ vendorName }) {
  const [activeRegion, setActiveRegion] = useState("Bay Area");
  const [searchQuery, setSearchQuery] = useState("");

  const { data: rates = [], isLoading } = useQuery({
    queryKey: ['vendor-rates', vendorName],
    queryFn: async () => {
      const allRates = await base44.entities.VendorRate.list();
      return allRates.filter(r => r.vendor_name === vendorName && r.is_active);
    },
    initialData: [],
    enabled: !!vendorName,
  });

  const ratesByRegion = useMemo(() => {
    const grouped = {};
    
    rates.forEach(rate => {
      let region = "National"; // Default region
      
      // Attempt to determine region from rate.notes first
      if (rate.notes) {
        const notesLower = rate.notes.toLowerCase();
        if (notesLower.includes("bay area") || notesLower.includes("san francisco")) {
          region = "Bay Area";
        } else if (notesLower.includes("southern california") || notesLower.includes("los angeles") || notesLower.includes("san diego")) {
          region = "Southern California";
        } else if (notesLower.includes("northern california") || notesLower.includes("sacramento")) {
          region = "Northern California";
        }
      }
      
      // If region is not determined by notes, try to parse from role_name
      if (region === "National" && parseRoleName(rate.role_name).region) {
          region = parseRoleName(rate.role_name).region;
      }

      if (!grouped[region]) {
        grouped[region] = [];
      }
      grouped[region].push(rate);
    });
    
    return grouped;
  }, [rates]);

  const filteredRates = useMemo(() => {
    const regionRates = ratesByRegion[activeRegion] || [];
    if (!searchQuery.trim()) return regionRates;
    
    const query = searchQuery.toLowerCase();
    return regionRates.filter(r => 
      parseRoleName(r.role_name).position.toLowerCase().includes(query) || // Search parsed position
      r.category?.toLowerCase().includes(query)
    );
  }, [ratesByRegion, activeRegion, searchQuery]);

  const regionStats = useMemo(() => {
    const regionRates = ratesByRegion[activeRegion] || [];
    return {
      totalRoles: regionRates.length,
      avgClientRate: regionRates.length > 0 
        ? regionRates.reduce((sum, r) => sum + (r.client_rate || 0), 0) / regionRates.length 
        : 0,
      avgMarkup: regionRates.length > 0
        ? regionRates.reduce((sum, r) => sum + (r.markup_percentage || 0), 0) / regionRates.length
        : 0,
      avgVendorFee: regionRates.length > 0
        ? regionRates.reduce((sum, r) => sum + (r.vendor_fee_percentage || 0), 0) / regionRates.length
        : 0
    };
  }, [ratesByRegion, activeRegion]);

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        <PageHeader 
          title={`Service Rates 2025-2028`}
          subtitle={`${vendorName} - Manage pricing across all clients and positions`}
          actions={
            <Button
              onClick={() => downloadCSV(filteredRates, activeRegion, vendorName)}
              variant="outline"
              className="border-slate-300"
            >
              <Download className="w-4 h-4 mr-2" />
              Export {activeRegion} Rates
            </Button>
          }
        />

        {/* Summary Stats */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          <Card className="border-slate-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-slate-600">Total Roles</p>
                  <p className="text-2xl font-bold text-[#1C323E]">{regionStats.totalRoles}</p>
                </div>
                <Building2 className="w-8 h-8 text-[#0A39DF]" />
              </div>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-slate-600">Avg Client Rate</p>
                  <p className="text-2xl font-bold text-[#1C323E]">{fmtCurrency(regionStats.avgClientRate)}</p>
                </div>
                <DollarSign className="w-8 h-8 text-emerald-600" />
              </div>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-slate-600">Avg Markup</p>
                  <p className="text-2xl font-bold text-[#1C323E]">{regionStats.avgMarkup.toFixed(1)}%</p>
                </div>
                <MapPin className="w-8 h-8 text-blue-600" />
              </div>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-slate-600">Avg VA Fee</p>
                  <p className="text-2xl font-bold text-[#1C323E]">{regionStats.avgVendorFee.toFixed(1)}%</p>
                </div>
                <DollarSign className="w-8 h-8 text-purple-600" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Region Tabs */}
        <Card className="mb-6 border-slate-200">
          <CardContent className="p-4">
            <div className="flex flex-wrap gap-2">
              {REGIONS.filter(region => ratesByRegion[region]?.length > 0).map(region => (
                <button
                  key={region}
                  onClick={() => setActiveRegion(region)}
                  className={`px-6 py-3 rounded-lg text-sm font-medium transition-all ${
                    activeRegion === region
                      ? "bg-[#0A39DF] text-white shadow-md"
                      : "bg-white text-slate-600 border border-slate-200 hover:border-[#0A39DF] hover:text-[#0A39DF]"
                  }`}
                >
                  {region}
                  <Badge variant="secondary" className="ml-2 bg-slate-100 text-slate-700">
                    {ratesByRegion[region]?.length || 0}
                  </Badge>
                </button>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Search Bar */}
        <div className="mb-6">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-slate-400" />
            <Input
              placeholder="Search roles or categories..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 bg-white border-slate-200"
            />
          </div>
        </div>

        {/* Rates Table */}
        <Card className="border-slate-200 shadow-sm">
          <CardHeader className="border-b border-slate-100 bg-gradient-to-br from-slate-50 to-white">
            <CardTitle className="text-lg font-semibold text-slate-900 flex items-center gap-2">
              <MapPin className="w-5 h-5 text-[#0A39DF]" />
              {activeRegion} Rates
            </CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            {filteredRates.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-slate-50 border-b-2 border-slate-200">
                    <tr>
                      <th className="text-left py-4 px-6 font-semibold text-sm text-slate-700">Position</th>
                      <th className="text-left py-4 px-6 font-semibold text-sm text-slate-700">Category</th>
                      <th className="text-left py-4 px-6 font-semibold text-sm text-slate-700">Region</th>
                      <th className="text-right py-4 px-6 font-semibold text-sm text-slate-700">Employee Wage</th>
                      <th className="text-right py-4 px-6 font-semibold text-sm text-slate-700">Markup</th>
                      <th className="text-right py-4 px-6 font-semibold text-sm text-slate-700">VA Fee</th>
                      <th className="text-right py-4 px-6 font-semibold text-sm text-slate-700">Client Rate</th>
                      <th className="text-center py-4 px-6 font-semibold text-sm text-slate-700">Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredRates.map((rate, idx) => {
                      const parsed = parseRoleName(rate.role_name);
                      
                      return (
                        <tr 
                          key={rate.id} 
                          className={`border-b border-slate-100 hover:bg-slate-50 transition-colors ${
                            idx % 2 === 0 ? 'bg-white' : 'bg-slate-50/30'
                          }`}
                        >
                          <td className="py-4 px-6">
                            <p className="font-semibold text-[#1C323E]">{parsed.position}</p>
                          </td>
                          <td className="py-4 px-6">
                            <Badge variant="outline" className="text-xs">
                              {rate.category}
                            </Badge>
                          </td>
                          <td className="py-4 px-6">
                            <p className="text-sm text-slate-600">{parsed.region || '—'}</p>
                          </td>
                          <td className="py-4 px-6 text-right">
                            <p className="font-medium text-slate-900">{fmtCurrency(rate.employee_wage)}</p>
                            <p className="text-xs text-slate-500">/hour</p>
                          </td>
                          <td className="py-4 px-6 text-right">
                            <p className="font-medium text-blue-600">{rate.markup_percentage}%</p>
                            <p className="text-xs text-slate-500">+{fmtCurrency(rate.employee_wage * (rate.markup_percentage / 100))}</p>
                          </td>
                          <td className="py-4 px-6 text-right">
                            <p className="font-medium text-purple-600">{rate.vendor_fee_percentage}%</p>
                            <p className="text-xs text-slate-500">+{fmtCurrency((rate.employee_wage * (1 + rate.markup_percentage / 100)) * (rate.vendor_fee_percentage / 100))}</p>
                          </td>
                          <td className="py-4 px-6 text-right">
                            <p className="text-2xl font-bold text-[#0A39DF]">{fmtCurrency(rate.client_rate)}</p>
                            <p className="text-xs text-slate-500">/hour</p>
                          </td>
                          <td className="py-4 px-6 text-center">
                            <div className="flex flex-col gap-1 items-center">
                              {rate.competitive_status && (
                                <Badge className="bg-green-100 text-green-700 text-xs">
                                  Competitive
                                </Badge>
                              )}
                              {rate.minimum_wage_compliance && (
                                <Badge className="bg-emerald-100 text-emerald-700 text-xs">
                                  Compliant
                                </Badge>
                              )}
                              {rate.csta_compliant && (
                                <Badge className="bg-blue-100 text-blue-700 text-xs">
                                  CSTA
                                </Badge>
                              )}
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            ) : (
              <div className="text-center py-16">
                <MapPin className="w-16 h-16 mx-auto text-slate-300 mb-4" />
                <h3 className="text-xl font-semibold text-slate-900 mb-2">
                  {searchQuery ? "No matching rates found" : `No rates for ${activeRegion}`}
                </h3>
                <p className="text-slate-600">
                  {searchQuery ? "Try adjusting your search" : "Contact your account manager to set up rates for this region"}
                </p>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Footer Info */}
        <div className="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
          <div className="flex items-start gap-3">
            <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center flex-shrink-0">
              <Building2 className="w-4 h-4 text-blue-600" />
            </div>
            <div>
              <h4 className="font-semibold text-slate-900 mb-1">About Your Rates</h4>
              <p className="text-sm text-slate-700">
                These are your approved service rates for {activeRegion}. Rates include employee wages, markup, and vendor administration fees. 
                All rates are compliant with regional minimum wage requirements and have been approved by procurement.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ==================== MAIN COMPONENT WITH ROLE-BASED ROUTING ====================
export default function VendorRates() {
  const { data: user } = useQuery({
    queryKey: ['current-user-vendor-rates'],
    queryFn: () => base44.auth.me(),
  });

  const userRole = user?.user_role || user?.role || "admin";
  const vendorName = user?.company_name || "Vendor";
  const isVendor = userRole === "vendor";

  // VENDOR ROLE: Show new company pricebook interface
  if (isVendor) {
    return <VendorCompanyPricebookView user={user} vendorName={vendorName} />;
  }

  // ALL OTHER ROLES: Show existing region-based rates view
  return <AdminProcurementRatesView vendorName={vendorName} />;
}
