import { useState, ReactNode } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { toast } from "sonner";
import { Plus, Pencil, Trash2, Tag, Percent, PoundSterling, Users, Building2, Globe } from "lucide-react";
import AdminLayout from "@/layouts/AdminLayout";

interface DiscountCode {
  id: string;
  code: string;
  discount_type: "percent" | "fixed";
  discount_percent: number;
  discount_amount_cents: number;
  scope: "general" | "company" | "user";
  company_id: string | null;
  user_id: string | null;
  max_uses: number | null;
  times_used: number;
  is_active: boolean;
  valid_from: string | null;
  valid_until: string | null;
  created_at: string;
}

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? "";

const emptyForm = (): Partial<DiscountCode> => ({
  code: "",
  discount_type: "percent",
  discount_percent: 10,
  discount_amount_cents: 0,
  scope: "general",
  company_id: null,
  user_id: null,
  max_uses: null,
  is_active: true,
  valid_from: null,
  valid_until: null,
});

const DiscountCodesPage = () => {
  const qc = useQueryClient();
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<DiscountCode | null>(null);
  const [form, setForm] = useState<Partial<DiscountCode>>(emptyForm());
  const [deleteId, setDeleteId] = useState<string | null>(null);

  const { data: codes = [], isLoading } = useQuery({
    queryKey: ["discount_codes"],
    queryFn: async (): Promise<DiscountCode[]> => {
      const res = await fetch("/api/admin/discount-codes");
      if (!res.ok) return [];
      return res.json();
    },
  });

  const { data: companies = [] } = useQuery({
    queryKey: ["companies_list"],
    queryFn: async (): Promise<any[]> => {
      const res = await fetch("/api/admin/training-companies?status=active");
      if (!res.ok) return [];
      return res.json();
    },
  });

  const saveMutation = useMutation({
    mutationFn: async (values: Partial<DiscountCode>) => {
      const payload: any = {
        code: values.code!.trim().toUpperCase(),
        discount_type: values.discount_type,
        discount_percent: values.discount_type === "percent" ? values.discount_percent : 0,
        discount_amount_cents: values.discount_type === "fixed" ? (values.discount_amount_cents || 0) : 0,
        scope: values.scope,
        company_id: values.scope === "company" ? values.company_id : null,
        user_id: values.scope === "user" ? values.user_id || null : null,
        max_uses: values.max_uses || null,
        is_active: values.is_active,
        valid_from: values.valid_from || null,
        valid_until: values.valid_until || null,
      };

      const path = editing
        ? `/api/admin/discount-codes/${editing.id}`
        : `/api/admin/discount-codes`;
      const method = editing ? "PUT" : "POST";
      const body = editing ? payload : { ...payload, times_used: 0 };
      const res = await fetch(path, {
        method,
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify(body),
      });
      if (!res.ok) throw new Error("Failed to save discount code");
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["discount_codes"] });
      toast.success(editing ? "Discount code updated" : "Discount code created");
      setDialogOpen(false);
    },
    onError: (err: any) => toast.error(err.message),
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const res = await fetch(`/api/admin/discount-codes/${id}`, {
        method: "DELETE",
        headers: { "X-CSRF-TOKEN": csrfToken() },
      });
      if (!res.ok) throw new Error("Failed to delete discount code");
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["discount_codes"] });
      toast.success("Discount code deleted");
      setDeleteId(null);
    },
    onError: (err: any) => toast.error(err.message),
  });

  const toggleActive = async (code: DiscountCode) => {
    try {
      const res = await fetch(`/api/admin/discount-codes/${code.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify({ is_active: !code.is_active }),
      });
      if (!res.ok) throw new Error("Failed to toggle active state");
      qc.invalidateQueries({ queryKey: ["discount_codes"] });
    } catch (err: any) {
      toast.error(err.message);
    }
  };

  const openCreate = () => {
    setEditing(null);
    setForm(emptyForm());
    setDialogOpen(true);
  };

  const openEdit = (code: DiscountCode) => {
    setEditing(code);
    setForm({ ...code });
    setDialogOpen(true);
  };

  const scopeIcon = (scope: string) => {
    if (scope === "company") return <Building2 className="w-3 h-3" />;
    if (scope === "user") return <Users className="w-3 h-3" />;
    return <Globe className="w-3 h-3" />;
  };

  const scopeLabel = (code: DiscountCode) => {
    if (code.scope === "company") {
      const co = companies.find((c: any) => c.id === code.company_id);
      return co ? co.name : "Company";
    }
    if (code.scope === "user") return code.user_id ? `User: ${code.user_id.slice(0, 8)}…` : "User";
    return "General";
  };

  const discountLabel = (code: DiscountCode) => {
    if (code.discount_type === "fixed") {
      return `£${(code.discount_amount_cents / 100).toFixed(2)} off`;
    }
    return `${code.discount_percent}% off`;
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Discount Codes</h1>
          <p className="text-muted-foreground text-sm mt-1">
            Create and manage promotional discount codes
          </p>
        </div>
        <Button onClick={openCreate}>
          <Plus className="w-4 h-4 mr-2" /> New Code
        </Button>
      </div>

      {isLoading ? (
        <div className="flex justify-center py-12">
          <div className="animate-spin w-6 h-6 border-2 border-primary border-t-transparent rounded-full" />
        </div>
      ) : codes.length === 0 ? (
        <div className="text-center py-16 border border-dashed border-border rounded-lg">
          <Tag className="w-10 h-10 text-muted-foreground mx-auto mb-3" />
          <p className="text-muted-foreground">No discount codes yet. Create one to get started.</p>
        </div>
      ) : (
        <div className="border border-border rounded-lg overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Code</TableHead>
                <TableHead>Discount</TableHead>
                <TableHead>Scope</TableHead>
                <TableHead>Usage</TableHead>
                <TableHead>Validity</TableHead>
                <TableHead>Active</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {codes.map((code) => (
                <TableRow key={code.id}>
                  <TableCell>
                    <span className="font-mono font-semibold text-foreground">{code.code}</span>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-1.5">
                      {code.discount_type === "fixed" ? (
                        <PoundSterling className="w-3.5 h-3.5 text-primary" />
                      ) : (
                        <Percent className="w-3.5 h-3.5 text-primary" />
                      )}
                      <span className="font-medium">{discountLabel(code)}</span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-1.5 text-sm text-muted-foreground">
                      {scopeIcon(code.scope)}
                      <span>{scopeLabel(code)}</span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <span className="text-sm">
                      {code.times_used}
                      {code.max_uses ? ` / ${code.max_uses}` : " / ∞"}
                    </span>
                  </TableCell>
                  <TableCell>
                    {code.valid_until ? (
                      <span className="text-sm text-muted-foreground">
                        Until {new Date(code.valid_until).toLocaleDateString("en-GB")}
                      </span>
                    ) : (
                      <span className="text-xs text-muted-foreground">No expiry</span>
                    )}
                  </TableCell>
                  <TableCell>
                    <Switch
                      checked={code.is_active}
                      onCheckedChange={() => toggleActive(code)}
                    />
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-2">
                      <Button variant="ghost" size="icon" onClick={() => openEdit(code)}>
                        <Pencil className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="text-destructive hover:text-destructive"
                        onClick={() => setDeleteId(code.id)}
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      {/* Create / Edit Dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>{editing ? "Edit Discount Code" : "New Discount Code"}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            {/* Code */}
            <div>
              <Label>Code *</Label>
              <Input
                value={form.code || ""}
                onChange={(e) => setForm((f) => ({ ...f, code: e.target.value.toUpperCase() }))}
                placeholder="e.g. SUMMER25"
                className="font-mono uppercase"
              />
            </div>

            {/* Discount Type */}
            <div>
              <Label>Discount Type *</Label>
              <Select
                value={form.discount_type || "percent"}
                onValueChange={(v) => setForm((f) => ({ ...f, discount_type: v as any }))}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="percent">Percentage (%)</SelectItem>
                  <SelectItem value="fixed">Fixed Amount (£)</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* Discount Value */}
            {form.discount_type === "percent" ? (
              <div>
                <Label>Discount Percentage *</Label>
                <div className="relative">
                  <Input
                    type="number"
                    min={1}
                    max={100}
                    value={form.discount_percent || ""}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, discount_percent: Math.min(100, parseInt(e.target.value) || 0) }))
                    }
                    placeholder="10"
                    className="pr-8"
                  />
                  <span className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm">%</span>
                </div>
              </div>
            ) : (
              <div>
                <Label>Fixed Discount Amount *</Label>
                <div className="relative">
                  <span className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm">£</span>
                  <Input
                    type="number"
                    min={0.01}
                    step={0.01}
                    value={form.discount_amount_cents ? (form.discount_amount_cents / 100).toFixed(2) : ""}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, discount_amount_cents: Math.round(parseFloat(e.target.value) * 100) || 0 }))
                    }
                    placeholder="25.00"
                    className="pl-7"
                  />
                </div>
              </div>
            )}

            {/* Scope */}
            <div>
              <Label>Applies To *</Label>
              <Select
                value={form.scope || "general"}
                onValueChange={(v) => setForm((f) => ({ ...f, scope: v as any, company_id: null, user_id: null }))}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="general">General Use (anyone)</SelectItem>
                  <SelectItem value="company">Specific Company</SelectItem>
                  <SelectItem value="user">Specific User (by User ID)</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {form.scope === "company" && (
              <div>
                <Label>Company *</Label>
                <Select
                  value={form.company_id || ""}
                  onValueChange={(v) => setForm((f) => ({ ...f, company_id: v }))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select company…" />
                  </SelectTrigger>
                  <SelectContent>
                    {companies.map((c: any) => (
                      <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}

            {form.scope === "user" && (
              <div>
                <Label>User ID *</Label>
                <Input
                  value={form.user_id || ""}
                  onChange={(e) => setForm((f) => ({ ...f, user_id: e.target.value }))}
                  placeholder="Paste user UUID"
                />
              </div>
            )}

            {/* Max Uses */}
            <div>
              <Label>Max Uses (leave blank for unlimited)</Label>
              <Input
                type="number"
                min={1}
                value={form.max_uses || ""}
                onChange={(e) =>
                  setForm((f) => ({ ...f, max_uses: parseInt(e.target.value) || null }))
                }
                placeholder="e.g. 50"
              />
            </div>

            {/* Validity */}
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>Valid From</Label>
                <Input
                  type="date"
                  value={form.valid_from ? form.valid_from.slice(0, 10) : ""}
                  onChange={(e) => setForm((f) => ({ ...f, valid_from: e.target.value || null }))}
                />
              </div>
              <div>
                <Label>Valid Until</Label>
                <Input
                  type="date"
                  value={form.valid_until ? form.valid_until.slice(0, 10) : ""}
                  onChange={(e) => setForm((f) => ({ ...f, valid_until: e.target.value || null }))}
                />
              </div>
            </div>

            {/* Active */}
            <div className="flex items-center gap-3">
              <Switch
                checked={form.is_active ?? true}
                onCheckedChange={(v) => setForm((f) => ({ ...f, is_active: v }))}
              />
              <Label>Active</Label>
            </div>

            <div className="flex justify-end gap-2 pt-2">
              <Button variant="outline" onClick={() => setDialogOpen(false)}>Cancel</Button>
              <Button
                onClick={() => saveMutation.mutate(form)}
                disabled={saveMutation.isPending || !form.code?.trim()}
              >
                {saveMutation.isPending ? "Saving…" : editing ? "Update" : "Create"}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Delete Confirm */}
      <Dialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
        <DialogContent className="sm:max-w-sm">
          <DialogHeader>
            <DialogTitle>Delete Discount Code?</DialogTitle>
          </DialogHeader>
          <p className="text-sm text-muted-foreground">
            This action cannot be undone. The code will be permanently removed.
          </p>
          <div className="flex justify-end gap-2 pt-2">
            <Button variant="outline" onClick={() => setDeleteId(null)}>Cancel</Button>
            <Button
              variant="destructive"
              onClick={() => deleteId && deleteMutation.mutate(deleteId)}
              disabled={deleteMutation.isPending}
            >
              {deleteMutation.isPending ? "Deleting…" : "Delete"}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
};

DiscountCodesPage.layout = (page: ReactNode) => <AdminLayout>{page}</AdminLayout>;

export default DiscountCodesPage;
