'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Plus, Edit, Trash2, Copy, Check } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Badge from '@/components/ui/Badge';
import ActionButton from '@/components/ui/ActionButton';
import Modal from '@/components/ui/Modal';
import ConfirmDialog from '@/components/ui/ConfirmDialog';
import { promosApi, PromoCode } from '@/lib/api/promos';

export default function PromosPage() {
  const [filters, setFilters] = useState({ search: '', active: '', page: 1, pageSize: 10 });
  const [showModal, setShowModal] = useState(false);
  const [editingPromo, setEditingPromo] = useState<any>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<{ isOpen: boolean; promo: any | null }>({ isOpen: false, promo: null });
  const [copiedCode, setCopiedCode] = useState<string | null>(null);
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['promos', filters],
    queryFn: () => promosApi.getAll(filters),
  });

  const createMutation = useMutation({
    mutationFn: promosApi.create,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['promos'] });
      setShowModal(false);
      setEditingPromo(null);
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => promosApi.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['promos'] });
      setShowModal(false);
      setEditingPromo(null);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: promosApi.delete,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['promos'] });
    },
  });

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    
    const promoData = {
      code: formData.get('code') as string,
      title: formData.get('title') as string,
      discountType: formData.get('discountType') as 'PERCENTAGE' | 'FIXED',
      discountValue: parseFloat(formData.get('discountValue') as string),
      maxDiscount: formData.get('maxDiscount') ? parseFloat(formData.get('maxDiscount') as string) : undefined,
      minBookingAmount: formData.get('minBookingAmount') ? parseFloat(formData.get('minBookingAmount') as string) : undefined,
      maxUsagePerUser: formData.get('maxUsagePerUser') ? parseInt(formData.get('maxUsagePerUser') as string) : undefined,
      totalUsageLimit: formData.get('totalUsageLimit') ? parseInt(formData.get('totalUsageLimit') as string) : undefined,
      validFrom: formData.get('validFrom') as string,
      validUntil: formData.get('validUntil') as string,
      isActive: formData.get('isActive') === 'true',
    };

    if (editingPromo) {
      await updateMutation.mutateAsync({ id: editingPromo.id, data: promoData });
    } else {
      await createMutation.mutateAsync(promoData);
    }
  };

  const handleDelete = (promo: any) => {
    setDeleteConfirm({ isOpen: true, promo });
  };

  const confirmDelete = async () => {
    if (deleteConfirm.promo) {
      await deleteMutation.mutateAsync(deleteConfirm.promo.id);
      setDeleteConfirm({ isOpen: false, promo: null });
    }
  };

  const copyToClipboard = (code: string) => {
    navigator.clipboard.writeText(code);
    setCopiedCode(code);
    setTimeout(() => setCopiedCode(null), 2000);
  };

  const columns = [
    {
      key: 'code',
      label: 'Promo Code',
      render: (promo: PromoCode) => (
        <div className="flex items-center gap-2">
          <span className="font-mono font-semibold text-lg">{promo.code}</span>
          <button
            onClick={() => copyToClipboard(promo.code)}
            className="p-1 hover:bg-gray-100 dark:hover:bg-gray-800 rounded transition-colors"
            title="Copy code"
          >
            {copiedCode === promo.code ? (
              <Check className="h-4 w-4 text-green-600" />
            ) : (
              <Copy className="h-4 w-4 text-muted-foreground" />
            )}
          </button>
        </div>
      ),
    },
    {
      key: 'title',
      label: 'Title',
      render: (promo: PromoCode) => (
        <span className="text-sm font-medium">{promo.title || '-'}</span>
      ),
    },
    {
      key: 'discount',
      label: 'Discount',
      render: (promo: PromoCode) => (
        <span className="font-semibold">
          {promo.discountType === 'PERCENTAGE' 
            ? `${promo.discountValue}%` 
            : `ETB ${promo.discountValue}`}
        </span>
      ),
    },
    {
      key: 'validity',
      label: 'Valid Period',
      render: (promo: PromoCode) => (
        <div className="text-sm">
          <div>{new Date(promo.validFrom).toLocaleDateString()}</div>
          <div className="text-muted-foreground">{new Date(promo.validUntil).toLocaleDateString()}</div>
        </div>
      ),
    },
    {
      key: 'usage',
      label: 'Usage',
      render: (promo: PromoCode) => (
        <div className="text-sm">
          <div>{promo.usageCount} used</div>
          {promo.totalUsageLimit && (
            <div className="text-muted-foreground">/ {promo.totalUsageLimit} limit</div>
          )}
        </div>
      ),
    },
    {
      key: 'status',
      label: 'Status',
      render: (promo: PromoCode) => (
        <Badge variant="status" status={promo.isActive ? 'CONFIRMED' : 'CANCELLED'}>
          {promo.isActive ? 'Active' : 'Inactive'}
        </Badge>
      ),
    },
  ];

  const actions = [
    {
      label: 'Edit',
      onClick: (promo: PromoCode) => {
        setEditingPromo(promo);
        setShowModal(true);
      },
      variant: 'secondary' as const,
      icon: Edit,
    },
    {
      label: 'Delete',
      onClick: handleDelete,
      variant: 'danger' as const,
      icon: Trash2,
    },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Promo Codes</h1>
          <p className="text-muted-foreground">Manage promotional codes and discounts</p>
        </div>
        <ActionButton
          icon={Plus}
          onClick={() => {
            setEditingPromo(null);
            setShowModal(true);
          }}
        >
          Add Promo Code
        </ActionButton>
      </div>

      {/* Filters */}
      <div className="card">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <input
              type="text"
              placeholder="Search promo codes..."
              className="input"
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value, page: 1 })}
            />
          </div>
          <div>
            <select
              className="input"
              value={filters.active}
              onChange={(e) => setFilters({ ...filters, active: e.target.value, page: 1 })}
            >
              <option value="">All Status</option>
              <option value="true">Active</option>
              <option value="false">Inactive</option>
            </select>
          </div>
        </div>
      </div>

      {/* Promos Table */}
      <DataTable
        data={data?.items || []}
        columns={columns}
        actions={actions}
        loading={isLoading}
        emptyMessage="No promo codes found"
      />

      {/* Delete Confirmation */}
      <ConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, promo: null })}
        onConfirm={confirmDelete}
        title="Delete Promo Code"
        message={`Are you sure you want to delete promo code "${deleteConfirm.promo?.code}"?`}
        confirmText="Delete"
        isDanger={true}
      />

      {/* Add/Edit Modal */}
      <Modal
        isOpen={showModal}
        onClose={() => {
          setShowModal(false);
          setEditingPromo(null);
        }}
        title={`${editingPromo ? 'Edit' : 'Create'} Promo Code`}
        size="lg"
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="label">Promo Code *</label>
              <input
                type="text"
                name="code"
                className="input uppercase"
                defaultValue={editingPromo?.code}
                required
                placeholder="e.g., SUMMER2024"
                maxLength={20}
                disabled={!!editingPromo}
              />
            </div>
            <div>
              <label className="label">Title *</label>
              <input
                type="text"
                name="title"
                className="input"
                defaultValue={editingPromo?.title}
                required
                placeholder="e.g., Summer Discount"
              />
            </div>
            <div>
              <label className="label">Discount Type *</label>
              <select
                name="discountType"
                className="input"
                defaultValue={editingPromo?.discountType || 'PERCENTAGE'}
                required
              >
                <option value="PERCENTAGE">Percentage (%)</option>
                <option value="FIXED">Fixed Amount (ETB)</option>
              </select>
            </div>
            <div>
              <label className="label">Discount Value *</label>
              <input
                type="number"
                name="discountValue"
                className="input"
                defaultValue={editingPromo?.discountValue}
                required
                placeholder="e.g., 15"
                min="0"
                step="0.01"
              />
            </div>
            <div>
              <label className="label">Max Discount (ETB)</label>
              <input
                type="number"
                name="maxDiscount"
                className="input"
                defaultValue={editingPromo?.maxDiscount}
                placeholder="e.g., 500"
                min="0"
                step="0.01"
              />
            </div>
            <div>
              <label className="label">Min Booking Amount (ETB)</label>
              <input
                type="number"
                name="minBookingAmount"
                className="input"
                defaultValue={editingPromo?.minBookingAmount}
                placeholder="e.g., 1000"
                min="0"
                step="0.01"
              />
            </div>
            <div>
              <label className="label">Max Usage Per User</label>
              <input
                type="number"
                name="maxUsagePerUser"
                className="input"
                defaultValue={editingPromo?.maxUsagePerUser}
                placeholder="Unlimited if empty"
                min="1"
              />
            </div>
            <div>
              <label className="label">Total Usage Limit</label>
              <input
                type="number"
                name="totalUsageLimit"
                className="input"
                defaultValue={editingPromo?.totalUsageLimit}
                placeholder="Unlimited if empty"
                min="1"
              />
            </div>
            <div>
              <label className="label">Valid From *</label>
              <input
                type="datetime-local"
                name="validFrom"
                className="input"
                defaultValue={editingPromo?.validFrom?.slice(0, 16)}
                required
              />
            </div>
            <div>
              <label className="label">Valid Until *</label>
              <input
                type="datetime-local"
                name="validUntil"
                className="input"
                defaultValue={editingPromo?.validUntil?.slice(0, 16)}
                required
              />
            </div>
            <div>
              <label className="label">Status</label>
              <select
                name="isActive"
                className="input"
                defaultValue={editingPromo?.isActive?.toString() || 'true'}
              >
                <option value="true">Active</option>
                <option value="false">Inactive</option>
              </select>
            </div>
          </div>

          <div className="flex justify-end gap-2 pt-4">
            <ActionButton
              type="button"
              variant="secondary"
              onClick={() => {
                setShowModal(false);
                setEditingPromo(null);
              }}
            >
              Cancel
            </ActionButton>
            <ActionButton
              type="submit"
              loading={createMutation.isPending || updateMutation.isPending}
            >
              {editingPromo ? 'Update' : 'Create'} Promo Code
            </ActionButton>
          </div>
        </form>
      </Modal>
    </div>
  );
}
