"use client";
import { useState } from "react";
import { Split, Plus, Trash2, Users, DollarSign } from "lucide-react";
import { ToolLayout } from "@/components/ToolLayout";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";

interface Item {
  id: string;
  name: string;
  amount: number;
}

interface Person {
  id: string;
  name: string;
  items: string[];
}

export default function SplitBillPage() {
  const [items, setItems] = useState<Item[]>([{ id: "1", name: "Item 1", amount: 0 }]);
  const [people, setPeople] = useState<Person[]>([
    { id: "1", name: "Person 1", items: [] },
    { id: "2", name: "Person 2", items: [] },
  ]);
  const [tax, setTax] = useState(0);
  const [tip, setTip] = useState(0);
  const [mode, setMode] = useState<"equal" | "itemized">("equal");

  const subtotal = items.reduce((s, i) => s + (i.amount || 0), 0);
  const taxAmt = subtotal * (tax / 100);
  const tipAmt = subtotal * (tip / 100);
  const total = subtotal + taxAmt + tipAmt;

  const addItem = () =>
    setItems((p) => [...p, { id: Date.now().toString(), name: `Item ${p.length + 1}`, amount: 0 }]);
  const removeItem = (id: string) => setItems((p) => p.filter((i) => i.id !== id));

  const addPerson = () =>
    setPeople((p) => [...p, { id: Date.now().toString(), name: `Person ${p.length + 1}`, items: [] }]);
  const removePerson = (id: string) => setPeople((p) => p.filter((x) => x.id !== id));

  const toggleItemForPerson = (personId: string, itemId: string) => {
    setPeople((p) =>
      p.map((person) =>
        person.id === personId
          ? {
              ...person,
              items: person.items.includes(itemId)
                ? person.items.filter((i) => i !== itemId)
                : [...person.items, itemId],
            }
          : person
      )
    );
  };

  const calcShare = (person: Person): number => {
    if (mode === "equal") {
      return people.length > 0 ? total / people.length : 0;
    }
    const personItems = items.filter((i) => person.items.includes(i.id));
    const personSubtotal = personItems.reduce((s, i) => s + (i.amount || 0), 0);
    const ratio = subtotal > 0 ? personSubtotal / subtotal : 1 / people.length;
    return personSubtotal + taxAmt * ratio + tipAmt * ratio;
  };

  const fmt = (n: number) =>
    n.toLocaleString("id-ID", { style: "currency", currency: "IDR", maximumFractionDigits: 0 });

  return (
    <ToolLayout icon={Split} title="Split Bill" description="Split bills easily and fairly among friends.">
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Left: Items */}
        <div className="space-y-4">
          <div className="glass-card rounded-xl p-4">
            <div className="flex items-center justify-between mb-3">
              <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60">Items</p>
              <Button variant="ghost" size="sm" onClick={addItem}>
                <Plus className="h-3.5 w-3.5 mr-1" /> Add Item
              </Button>
            </div>
            <div className="space-y-2">
              {items.map((item) => (
                <div key={item.id} className="flex items-center gap-2">
                  <Input
                    value={item.name}
                    onChange={(e) => setItems((p) => p.map((i) => i.id === item.id ? { ...i, name: e.target.value } : i))}
                    className="flex-1 h-8 text-xs"
                    placeholder="Item name"
                  />
                  <Input
                    type="number"
                    value={item.amount || ""}
                    onChange={(e) => setItems((p) => p.map((i) => i.id === item.id ? { ...i, amount: parseFloat(e.target.value) || 0 } : i))}
                    className="w-28 h-8 text-xs"
                    placeholder="0"
                  />
                  <Button variant="ghost" size="icon" className="h-8 w-8 shrink-0" onClick={() => removeItem(item.id)}>
                    <Trash2 className="h-3.5 w-3.5 text-muted-foreground" />
                  </Button>
                </div>
              ))}
            </div>
          </div>

          <div className="glass-card rounded-xl p-4">
            <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60 mb-3">Tax & Tip</p>
            <div className="grid grid-cols-2 gap-2">
              <div>
                <label className="text-xs text-muted-foreground mb-1 block">Tax %</label>
                <Input type="number" value={tax || ""} onChange={(e) => setTax(parseFloat(e.target.value) || 0)} placeholder="0" className="h-8 text-xs" />
              </div>
              <div>
                <label className="text-xs text-muted-foreground mb-1 block">Tip %</label>
                <Input type="number" value={tip || ""} onChange={(e) => setTip(parseFloat(e.target.value) || 0)} placeholder="0" className="h-8 text-xs" />
              </div>
            </div>
          </div>

          {/* Summary */}
          <div className="glass-card rounded-xl p-4">
            <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60 mb-3">Summary</p>
            <div className="space-y-1.5">
              <div className="flex justify-between text-sm"><span className="text-muted-foreground">Subtotal</span><span>{fmt(subtotal)}</span></div>
              <div className="flex justify-between text-sm"><span className="text-muted-foreground">Tax ({tax}%)</span><span>{fmt(taxAmt)}</span></div>
              <div className="flex justify-between text-sm"><span className="text-muted-foreground">Tip ({tip}%)</span><span>{fmt(tipAmt)}</span></div>
              <div className="flex justify-between text-sm font-semibold pt-2 border-t border-border"><span>Total</span><span>{fmt(total)}</span></div>
            </div>
          </div>
        </div>

        {/* Right: People */}
        <div className="space-y-4">
          <div className="glass-card rounded-xl p-4">
            <div className="flex items-center justify-between mb-3">
              <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60">People</p>
              <div className="flex items-center gap-1">
                <button
                  onClick={() => setMode("equal")}
                  className={`px-2 py-1 rounded text-xs ${mode === "equal" ? "bg-white text-black" : "text-muted-foreground hover:text-foreground"}`}
                >
                  Equal
                </button>
                <button
                  onClick={() => setMode("itemized")}
                  className={`px-2 py-1 rounded text-xs ${mode === "itemized" ? "bg-white text-black" : "text-muted-foreground hover:text-foreground"}`}
                >
                  Itemized
                </button>
                <Button variant="ghost" size="sm" onClick={addPerson}>
                  <Plus className="h-3.5 w-3.5 mr-1" /> Add
                </Button>
              </div>
            </div>
            <div className="space-y-3">
              {people.map((person) => (
                <div key={person.id} className="border border-border/50 rounded-lg p-3">
                  <div className="flex items-center gap-2 mb-2">
                    <Input
                      value={person.name}
                      onChange={(e) => setPeople((p) => p.map((x) => x.id === person.id ? { ...x, name: e.target.value } : x))}
                      className="flex-1 h-8 text-xs"
                    />
                    <Button variant="ghost" size="icon" className="h-8 w-8 shrink-0" onClick={() => removePerson(person.id)}>
                      <Trash2 className="h-3.5 w-3.5 text-muted-foreground" />
                    </Button>
                  </div>
                  {mode === "itemized" && (
                    <div className="flex flex-wrap gap-1 mb-2">
                      {items.map((item) => (
                        <button
                          key={item.id}
                          onClick={() => toggleItemForPerson(person.id, item.id)}
                          className={`px-2 py-0.5 rounded text-xs border transition-colors ${person.items.includes(item.id) ? "badge-ok border-transparent" : "border-border text-muted-foreground hover:border-white/30"}`}
                        >
                          {item.name}
                        </button>
                      ))}
                    </div>
                  )}
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-muted-foreground">
                      {mode === "itemized" ? `${person.items.length} item(s)` : "Equal share"}
                    </span>
                    <span className="text-sm font-semibold badge-ok px-2 py-0.5 rounded-lg">
                      {fmt(calcShare(person))}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Per person summary */}
          <div className="glass-card rounded-xl p-4">
            <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60 mb-3">Each Pays</p>
            <div className="space-y-2">
              {people.map((p) => (
                <div key={p.id} className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <div className="h-6 w-6 rounded-full bg-white/10 flex items-center justify-center">
                      <Users className="h-3 w-3" />
                    </div>
                    <span className="text-sm">{p.name}</span>
                  </div>
                  <div className="flex items-center gap-1 text-sm font-medium">
                    <DollarSign className="h-3 w-3 text-muted-foreground" />
                    {fmt(calcShare(p))}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </ToolLayout>
  );
}
