'use client';

import React, { useState } from 'react';
import { Plus, Search, Eye, EyeOff, Ticket, Package } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { DataTable, Column } from '@/components/ui/data-table';
import { TableSkeleton } from '@/components/ui/tableSkeleton';
import { useCoupons, useToggleCouponVisibility } from '@/services/coupons/queries';
import { useCouponGroups } from '@/services/coupon-groups/queries';
import { CouponRecord } from '@/services/coupons/types';
import GenerateCouponsModal from './_components/GenerateCouponsModal';
import CouponGroupsModal from './_components/createCouponGroupModal';

const STATUS_STYLES: Record<string, string> = {
  AVAILABLE: 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20',
  ASSIGNED_TO_DSO: 'bg-sky-500/10 text-sky-500 border-sky-500/20',
  ASSIGNED_TO_INSTITUTE: 'bg-indigo-500/10 text-indigo-500 border-indigo-500/20',
  ASSIGNED_TO_CAREER_ADVISOR: 'bg-violet-500/10 text-violet-500 border-violet-500/20',
  REDEEMED: 'bg-muted/40 text-muted-foreground border-border/40',
  HIDDEN: 'bg-muted/40 text-muted-foreground border-border/40',
  REVOKED: 'bg-destructive/10 text-destructive border-destructive/20',
};

export default function CouponsPage() {
  const [page, setPage] = useState(1);
  const [status, setStatus] = useState('');
  const [search, setSearch] = useState('');
  const [groupId, setGroupId] = useState('');
  const [showGenerateModal, setShowGenerateModal] = useState(false);
  const [showGroupsModal, setShowGroupsModal] = useState(false);

  const { data, isLoading } = useCoupons(page, status, search, 'all', groupId);
  const { data: groups } = useCouponGroups(undefined, false);
  const toggleVisibility = useToggleCouponVisibility();

  const columns: Column<CouponRecord>[] = [
    {
      header: 'Coupon Code',
      className: 'w-48',
      cell: (c) => (
        <div className="flex flex-col">
          <span className="font-mono text-xs font-bold text-primary">{c.code}</span>
          <span className="font-mono text-[10px] text-muted-foreground/60">
            {c.isHidden ? '•••• hidden ••••' : c.officialCode}
          </span>
          {/* Kit coupons carry a second, exam-specific code pair */}
          {c.group?.type === 'KIT' && c.examCode && (
            <span className="font-mono text-[10px] text-purple-500/80 mt-0.5">
              Exam: {c.examCode} {c.isHidden ? '' : `/ ${c.examOfficialCode}`}
            </span>
          )}
        </div>
      ),
    },
    {
      header: 'Group',
      className: 'w-32',
      cell: (c) => (
        <span
          className={`inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-bold rounded-full border uppercase ${
            c.group?.type === 'KIT'
              ? 'bg-purple-500/10 text-purple-500 border-purple-500/20'
              : 'bg-muted/40 text-muted-foreground border-border/40'
          }`}
        >
          {c.group?.type === 'KIT' && <Package className="h-2.5 w-2.5" />}
          {c.group?.name || '—'}
        </span>
      ),
    },
    {
      header: 'Status',
      className: 'w-44',
      cell: (c) => (
        <span
          className={`inline-flex px-2 py-0.5 text-[10px] font-bold rounded-full border uppercase ${
            STATUS_STYLES[c.status] || 'bg-muted/40 text-muted-foreground border-border/40'
          }`}
        >
          {c.status.replace(/_/g, ' ')}
        </span>
      ),
    },
    {
      header: 'Holder',
      className: 'min-w-[180px]',
      cell: (c) => (
        <span className="text-xs font-medium text-foreground">
          {c.assignedDsoUser
            ? `${c.assignedDsoUser.firstName} ${c.assignedDsoUser.lastName} (DSO)`
            : c.assignedInstitute
            ? `${c.assignedInstitute.name} (Institute)`
            : c.assignedCareerAdvisor
            ? `${c.assignedCareerAdvisor.name} (Advisor)`
            : '—'}
        </span>
      ),
    },
    {
      header: 'Created',
      className: 'w-32',
      cell: (c) => <span className="text-[11px] text-muted-foreground/70">{new Date(c.createdAt).toLocaleDateString()}</span>,
    },
    {
      header: 'Actions',
      className: 'w-28 text-right',
      cell: (c) => (
        <Button
          variant="ghost"
          size="sm"
          onClick={() => toggleVisibility.mutate({ id: c.id, isHidden: !c.isHidden })}
          className="h-7 px-2 text-[10px] font-bold gap-1"
        >
          {c.isHidden ? <Eye className="h-3 w-3" /> : <EyeOff className="h-3 w-3" />}
          {c.isHidden ? 'Reveal' : 'Hide'}
        </Button>
      ),
    },
  ];

  if (isLoading) return <TableSkeleton />;

  return (
    <>
      <div className="space-y-4 max-w-7xl mx-auto animate-in fade-in duration-300">
        <div className="flex items-center justify-between border-b border-border/10 pb-4">
          <div className="space-y-0.5">
            <h1 className="text-sm font-black tracking-widest text-foreground uppercase flex items-center gap-2">
              <Ticket className="h-4 w-4 text-primary" /> Coupon Inventory
            </h1>
            <p className="text-[11px] font-medium text-muted-foreground/70">
              {data?.statusCounts?.AVAILABLE ?? 0} coupon(s) available in the central pool.
            </p>
          </div>

          <div className="flex items-center gap-2">
            <Button
              onClick={() => setShowGroupsModal(true)}
              variant="outline"
              className="h-8 rounded-md px-3 text-[11px] font-bold tracking-wider uppercase gap-1.5"
            >
              <Package className="h-3.5 w-3.5" /> Manage Groups
            </Button>
            <Button
              onClick={() => setShowGenerateModal(true)}
              className="h-8 rounded-md px-3 text-[11px] font-bold tracking-wider uppercase shadow-sm gap-1.5 bg-foreground text-background hover:bg-foreground/90"
            >
              <Plus className="h-3.5 w-3.5 stroke-[2.5]" /> Generate Batch
            </Button>
          </div>
        </div>

        <div className="flex flex-wrap items-center justify-between gap-3">
          <div className="flex items-center max-w-xs w-full relative">
            <Search className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground/60" />
            <input
              type="text"
              placeholder="Search by code…"
              value={search}
              onChange={(e) => {
                setSearch(e.target.value);
                setPage(1);
              }}
              className="w-full text-xs font-medium pl-8 pr-3 py-2 border border-border/40 bg-surface rounded-lg text-foreground focus:outline-none focus:border-primary"
            />
          </div>

          <div className="flex items-center gap-2">
            <select
              value={groupId}
              onChange={(e) => {
                setGroupId(e.target.value);
                setPage(1);
              }}
              className="text-xs font-medium px-3 py-2 border border-border/40 bg-surface rounded-lg text-foreground focus:outline-none focus:border-primary"
            >
              <option value="">All Groups</option>
              {groups?.map((g) => (
                <option key={g.id} value={g.id}>
                  {g.name} {g.type === 'KIT' ? '(Kit)' : ''}
                </option>
              ))}
            </select>

            <select
              value={status}
              onChange={(e) => {
                setStatus(e.target.value);
                setPage(1);
              }}
              className="text-xs font-medium px-3 py-2 border border-border/40 bg-surface rounded-lg text-foreground focus:outline-none focus:border-primary"
            >
              <option value="">All Statuses</option>
              <option value="AVAILABLE">Available</option>
              <option value="ASSIGNED_TO_DSO">Assigned to DSO</option>
              <option value="ASSIGNED_TO_INSTITUTE">Assigned to Institute</option>
              <option value="ASSIGNED_TO_CAREER_ADVISOR">Assigned to Advisor</option>
              <option value="REDEEMED">Redeemed</option>
              <option value="REVOKED">Revoked</option>
            </select>
          </div>
        </div>

        <DataTable
          data={data?.items || []}
          columns={columns}
          emptyMessage="No coupons found matching current filters."
          pagination={
            data ? { page: data.page, pages: data.pages, total: data.total, onPageChange: setPage } : undefined
          }
        />
      </div>

      {showGenerateModal && <GenerateCouponsModal onClose={() => setShowGenerateModal(false)} />}
      {showGroupsModal && <CouponGroupsModal onClose={() => setShowGroupsModal(false)} />}
    </>
  );
}