import React, { useState, useMemo } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Slider } from "@/components/ui/slider";
import { Sparkles, DollarSign } from "lucide-react";

const APPROVED_BASE_RATES = {
  "FoodBuy": {
    "Banquet Captain": 47.76, "Barback": 36.13, "Barista": 43.11, "Busser": 39.23, "BW Bartender": 41.15,
    "Cashier/Standworker": 38.05, "Cook": 44.58, "Dinning Attendant": 41.56, "Dishwasher/ Steward": 38.38,
    "Executive Chef": 70.60, "FOH Cafe Attendant": 41.56, "Full Bartender": 47.76, "Grill Cook": 44.58,
    "Host/Hostess/Greeter": 41.56, "Internal Support": 41.56, "Lead Cook": 52.00, "Line Cook": 44.58,
    "Premium Server": 47.76, "Prep Cook": 37.98, "Receiver": 40.01, "Server": 41.56, "Sous Chef": 59.75,
    "Warehouse Worker": 41.15, "Baker": 44.58, "Janitor": 38.38, "Mixologist": 71.30, "Utilities": 38.38,
    "Scullery": 38.38, "Runner": 39.23, "Pantry Cook": 44.58, "Supervisor": 47.76, "Steward": 38.38, "Steward Supervisor": 41.15
  },
  "Aramark": {
    "Banquet Captain": 46.37, "Barback": 33.11, "Barista": 36.87, "Busser": 33.11, "BW Bartender": 36.12,
    "Cashier/Standworker": 33.11, "Cook": 36.12, "Dinning Attendant": 34.62, "Dishwasher/ Steward": 33.11,
    "Executive Chef": 76.76, "FOH Cafe Attendant": 34.62, "Full Bartender": 45.15, "Grill Cook": 36.12,
    "Host/Hostess/Greeter": 34.62, "Internal Support": 37.63, "Lead Cook": 52.68, "Line Cook": 36.12,
    "Premium Server": 40.64, "Prep Cook": 34.62, "Receiver": 34.62, "Server": 34.62, "Sous Chef": 60.20,
    "Warehouse Worker": 34.62, "Baker": 45.15, "Janitor": 34.62, "Mixologist": 60.20, "Utilities": 33.11,
    "Scullery": 33.11, "Runner": 33.11, "Pantry Cook": 36.12, "Supervisor": 45.15, "Steward": 33.11, "Steward Supervisor": 34.10
  }
};

export default function RateCardModal({ isOpen, onClose, onSave, editingCard = null }) {
  const [cardName, setCardName] = useState("");
  const [baseRateBook, setBaseRateBook] = useState("FoodBuy");
  const [discountPercent, setDiscountPercent] = useState(0);

  // Reset form when modal opens/closes or editingCard changes
  React.useEffect(() => {
    if (isOpen) {
      setCardName(editingCard?.name || "");
      setBaseRateBook(editingCard?.baseBook || "FoodBuy");
      setDiscountPercent(editingCard?.discount || 0);
    }
  }, [isOpen, editingCard]);

  const baseRates = APPROVED_BASE_RATES[baseRateBook] || {};
  const positions = Object.keys(baseRates);

  const stats = useMemo(() => {
    const rates = Object.values(baseRates);
    const avgBase = rates.length > 0 ? rates.reduce((a, b) => a + b, 0) / rates.length : 0;
    const avgNew = avgBase * (1 - discountPercent / 100);
    const totalSavings = rates.reduce((sum, r) => sum + (r * discountPercent / 100), 0);
    return { avgBase, avgNew, totalSavings, count: rates.length };
  }, [baseRates, discountPercent]);

  const handleSave = () => {
    if (!cardName.trim()) return;
    
    const discountedRates = {};
    Object.entries(baseRates).forEach(([pos, rate]) => {
      discountedRates[pos] = Math.round(rate * (1 - discountPercent / 100) * 100) / 100;
    });

    onSave({
      name: cardName,
      baseBook: baseRateBook,
      discount: discountPercent,
      rates: discountedRates
    });
    onClose();
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-3 text-xl">
            <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-xl flex items-center justify-center">
              <Sparkles className="w-5 h-5 text-white" />
            </div>
            {editingCard ? "Edit Rate Card" : "Create Custom Rate Card"}
          </DialogTitle>
          <p className="text-sm text-slate-500 mt-1">
            Build a custom rate card by selecting an approved rate book as your base and applying your competitive discount
          </p>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto space-y-6 py-4">
          {/* Step 1: Name */}
          <div className="bg-slate-50 rounded-xl p-5 border border-slate-200">
            <div className="flex items-center gap-2 mb-3">
              <div className="w-6 h-6 bg-green-500 rounded-full flex items-center justify-center text-white text-xs font-bold">1</div>
              <h3 className="font-semibold text-slate-900">
                {editingCard ? "Rename Rate Card" : "Name Your Rate Card"}
              </h3>
            </div>
            <Input
              value={cardName}
              onChange={(e) => setCardName(e.target.value)}
              placeholder="e.g., Google Campus, Meta HQ, Salesforce Tower..."
              className="bg-white text-lg font-medium"
              autoFocus={!!editingCard}
            />
            {editingCard && editingCard.name !== cardName && cardName.trim() && (
              <p className="text-sm text-green-600 mt-2 flex items-center gap-1">
                <span>✓</span> Will rename from "{editingCard.name}" to "{cardName}"
              </p>
            )}
          </div>

          {/* Step 2: Base Rates */}
          <div className="bg-amber-50 rounded-xl p-5 border border-amber-200">
            <div className="flex items-center gap-2 mb-3">
              <div className="w-6 h-6 bg-amber-500 rounded-full flex items-center justify-center text-white text-xs font-bold">2</div>
              <h3 className="font-semibold text-slate-900">Choose Approved Base Rates</h3>
            </div>
            <Select value={baseRateBook} onValueChange={setBaseRateBook}>
              <SelectTrigger className="bg-white">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="FoodBuy">FoodBuy Approved Rates</SelectItem>
                <SelectItem value="Aramark">Aramark Approved Rates</SelectItem>
              </SelectContent>
            </Select>
            <p className="text-sm text-amber-700 mt-2">
              Using {baseRateBook} as your baseline • Avg Rate: ${stats.avgBase.toFixed(2)}/hr
            </p>
          </div>

          {/* Step 3: Discount */}
          <div className="bg-blue-50 rounded-xl p-5 border border-blue-200">
            <div className="flex items-center gap-2 mb-4">
              <div className="w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center text-white text-xs font-bold">3</div>
              <h3 className="font-semibold text-slate-900">Apply Your Discount</h3>
            </div>
            <div className="flex items-center gap-6">
              <div className="flex-1">
                <Slider
                  value={[discountPercent]}
                  onValueChange={([val]) => setDiscountPercent(val)}
                  min={0}
                  max={25}
                  step={0.5}
                  className="[&_[role=slider]]:bg-green-500 [&_[role=slider]]:border-green-600"
                />
              </div>
              <div className="px-6 py-3 bg-white border-2 border-green-400 rounded-xl text-center min-w-[100px]">
                <span className="text-2xl font-bold text-green-600">% {discountPercent.toFixed(1)}%</span>
              </div>
            </div>
            <div className="flex items-center gap-4 mt-4 text-sm">
              <span className="text-slate-600">
                <span className="text-slate-400">↘</span> New Avg Rate: <strong className="text-slate-900">${stats.avgNew.toFixed(2)}/hr</strong>
              </span>
              <span className="text-slate-400">•</span>
              <span className="text-slate-600">
                Total Savings: <strong className="text-green-600">${stats.totalSavings.toFixed(2)}/position</strong>
              </span>
            </div>
          </div>

          {/* Rate Preview */}
          <div className="border border-slate-200 rounded-xl overflow-hidden">
            <div className="bg-slate-50 px-5 py-3 border-b border-slate-200 flex items-center gap-2">
              <DollarSign className="w-4 h-4 text-slate-600" />
              <h3 className="font-semibold text-slate-900">Rate Preview ({stats.count} positions)</h3>
            </div>
            <div className="max-h-[250px] overflow-y-auto">
              <table className="w-full text-sm">
                <thead className="bg-slate-50 sticky top-0">
                  <tr className="text-left text-slate-600">
                    <th className="px-5 py-2 font-medium">Position</th>
                    <th className="px-5 py-2 font-medium text-right">Base Rate</th>
                    <th className="px-5 py-2 font-medium text-right">Your Rate</th>
                    <th className="px-5 py-2 font-medium text-right">Savings</th>
                  </tr>
                </thead>
                <tbody>
                  {positions.map((position) => {
                    const baseRate = baseRates[position];
                    const newRate = baseRate * (1 - discountPercent / 100);
                    const savings = baseRate - newRate;
                    return (
                      <tr key={position} className="border-t border-slate-100 hover:bg-slate-50">
                        <td className="px-5 py-3 font-medium text-slate-900">{position}</td>
                        <td className="px-5 py-3 text-right text-slate-500">${baseRate.toFixed(2)}</td>
                        <td className="px-5 py-3 text-right font-semibold text-green-600">${newRate.toFixed(2)}</td>
                        <td className="px-5 py-3 text-right">
                          <span className="px-2 py-1 bg-green-100 text-green-700 rounded-md text-xs font-medium">
                            -${savings.toFixed(2)}
                          </span>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="flex justify-end gap-3 pt-4 border-t border-slate-200">
          <Button variant="outline" onClick={onClose}>Cancel</Button>
          <Button 
            onClick={handleSave}
            disabled={!cardName.trim()}
            className="bg-gradient-to-r from-purple-500 to-indigo-600 hover:from-purple-600 hover:to-indigo-700 text-white"
          >
            <Sparkles className="w-4 h-4 mr-2" />
            {editingCard ? "Save Changes" : "Create Rate Card"}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}