'use client';

import React, { useState } from 'react';
import { Package, Plus, ToggleLeft, ToggleRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Modal } from '@/components/ui/modal';
import { useCouponGroups, useCreateCouponGroup, useToggleCouponGroupActive } from '@/services/coupon-groups/queries';
import { CouponGroupType } from '@/services/coupon-groups/types';

interface Props {
  onClose: () => void;
}

export default function CouponGroupsModal({ onClose }: Props) {
  const { data: groups, isLoading } = useCouponGroups();
  const createMutation = useCreateCouponGroup();
  const toggleMutation = useToggleCouponGroupActive();

  const [showForm, setShowForm] = useState(false);
  const [name, setName] = useState('');
  const [type, setType] = useState<CouponGroupType>('NORMAL');
  const [price, setPrice] = useState('');
  const [description, setDescription] = useState('');
  const [kitComponentsText, setKitComponentsText] = useState('self_assignment_book, text_book, video_coupon, exam_coupon, certificate');
  const [error, setError] = useState<string | null>(null);

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (!name.trim()) {
      setError('Group name is required — e.g. "Cat 1" or "Kit 3".');
      return;
    }

    try {
      await createMutation.mutateAsync({
        name: name.trim(),
        type,
        price: price ? Number(price) : undefined,
        description: description.trim() || undefined,
        includesExamCoupon: type === 'KIT',
        kitComponents:
          type === 'KIT'
            ? kitComponentsText.split(',').map((c) => c.trim()).filter(Boolean)
            : undefined,
      });
      setShowForm(false);
      setName('');
      setPrice('');
      setDescription('');
    } catch {
      // handled by mutation toast
    }
  };

  return (
    <Modal onClose={onClose} icon={Package} iconClassName="text-primary" title="Coupon Groups">
      <div className="p-4 space-y-4">
        <div className="flex items-center justify-between">
          <p className="text-[11px] font-medium text-muted-foreground/70">
            A group must exist before coupons can be generated or a PO can be raised against it.
          </p>
          <Button
            type="button"
            size="sm"
            onClick={() => setShowForm((v) => !v)}
            className="h-7 px-2.5 text-[10px] font-bold gap-1"
          >
            <Plus className="h-3 w-3" /> New Group
          </Button>
        </div>

        {showForm && (
          <form onSubmit={handleCreate} className="p-3 rounded-lg border border-border/50 bg-muted/10 space-y-3">
            {error && (
              <div className="p-2 rounded-lg border border-destructive/20 bg-destructive/5 text-destructive text-[10px] font-medium">
                {error}
              </div>
            )}

            <div className="grid grid-cols-2 gap-2">
              <div>
                <label className="block text-[10px] font-bold uppercase text-muted-foreground mb-1">Name *</label>
                <input
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="e.g. Cat 1 or Kit 3"
                  className="w-full text-xs font-medium px-2.5 py-1.5 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
                  required
                />
              </div>
              <div>
                <label className="block text-[10px] font-bold uppercase text-muted-foreground mb-1">Type *</label>
                <select
                  value={type}
                  onChange={(e) => setType(e.target.value as CouponGroupType)}
                  className="w-full text-xs font-medium px-2.5 py-1.5 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
                >
                  <option value="NORMAL">Normal — online coupon only</option>
                  <option value="KIT">Kit — hybrid, includes exam coupon</option>
                </select>
              </div>
            </div>

            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground mb-1">Price</label>
              <input
                type="number"
                min={0}
                value={price}
                onChange={(e) => setPrice(e.target.value)}
                placeholder="e.g. 720"
                className="w-full text-xs font-medium px-2.5 py-1.5 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
            </div>

            {type === 'KIT' && (
              <div>
                <label className="block text-[10px] font-bold uppercase text-muted-foreground mb-1">
                  Kit Components (comma separated)
                </label>
                <textarea
                  value={kitComponentsText}
                  onChange={(e) => setKitComponentsText(e.target.value)}
                  rows={2}
                  className="w-full text-xs font-medium p-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
                />
                <p className="text-[10px] text-muted-foreground/60 mt-1">
                  Every coupon generated under a Kit group will also get an exam sub-code automatically.
                </p>
              </div>
            )}

            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground mb-1">Description</label>
              <input
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Optional"
                className="w-full text-xs font-medium px-2.5 py-1.5 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
            </div>

            <div className="flex justify-end gap-2">
              <Button type="button" variant="ghost" size="sm" onClick={() => setShowForm(false)} className="h-7 text-[10px] font-bold">
                Cancel
              </Button>
              <Button type="submit" size="sm" disabled={createMutation.isPending} className="h-7 text-[10px] font-bold">
                {createMutation.isPending ? 'Creating…' : 'Create Group'}
              </Button>
            </div>
          </form>
        )}

        {isLoading ? (
          <p className="text-xs text-muted-foreground text-center py-6">Loading groups…</p>
        ) : !groups || groups.length === 0 ? (
          <p className="text-xs text-muted-foreground text-center py-6">No coupon groups yet — create one above.</p>
        ) : (
          <div className="max-h-72 overflow-y-auto space-y-1.5">
            {groups.map((g) => (
              <div
                key={g.id}
                className="flex items-center justify-between p-2.5 rounded-lg border border-border/40 bg-background"
              >
                <div className="flex flex-col">
                  <div className="flex items-center gap-1.5">
                    <span className="text-xs font-bold text-foreground">{g.name}</span>
                    <span
                      className={`text-[9px] font-bold uppercase px-1.5 py-0.5 rounded-full border ${
                        g.type === 'KIT'
                          ? 'bg-purple-500/10 text-purple-500 border-purple-500/20'
                          : 'bg-muted/40 text-muted-foreground border-border/40'
                      }`}
                    >
                      {g.type}
                    </span>
                  </div>
                  <span className="text-[10px] text-muted-foreground/70">
                    {g.price != null ? `₹${g.price}` : 'No price set'} · {g._count?.coupons ?? 0} coupon(s) generated
                  </span>
                </div>
                <button
                  type="button"
                  onClick={() => toggleMutation.mutate({ id: g.id, isActive: !g.isActive })}
                  className="text-muted-foreground hover:text-primary"
                  title={g.isActive ? 'Deactivate group' : 'Activate group'}
                >
                  {g.isActive ? <ToggleRight className="h-5 w-5 text-emerald-500" /> : <ToggleLeft className="h-5 w-5" />}
                </button>
              </div>
            ))}
          </div>
        )}
      </div>
    </Modal>
  );
}