'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Plus, RefreshCw, Send, Trash2 } 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 { excessBaggageApi, apiClient } from '@/lib/api';
import { formatDateTime, formatCurrency } from '@/lib/utils';
import { useAuthStore } from '@/lib/auth-store';

const STATUS_VARIANT: Record<string, any> = {
  PENDING: 'PENDING',
  PAID: 'CONFIRMED',
  CASH_COLLECTED: 'CONFIRMED',
  EXPIRED: 'CANCELLED',
  WAIVED: 'CANCELLED',
};

export default function ExcessBaggagePage() {
  const queryClient = useQueryClient();
  const [filters, setFilters] = useState({ status: '', bookingRef: '', dateFrom: '', dateTo: '', page: '1' });
  const [showExtraFilters, setShowExtraFilters] = useState(false);
  const user = useAuthStore((s) => s.user);
  const [waiveModal, setWaiveModal] = useState<any>(null);
  const [waiveReason, setWaiveReason] = useState('');
  const [waiveError, setWaiveError] = useState<string | null>(null);
  const [logModal, setLogModal] = useState(false);
  const [logForm, setLogForm] = useState({ bookingId: '', excessWeightKg: '', collectCash: false });
  const [logError, setLogError] = useState<string | null>(null);
  const [resendModal, setResendModal] = useState<any>(null);
  const [resendSuccess, setResendSuccess] = useState(false);
  const [resendError, setResendError] = useState<string | null>(null);

  const { data: allowancesData } = useQuery({
    queryKey: ['baggage-allowances'],
    queryFn: () => apiClient.get<any>('/agents/excess-baggage/allowances'),
  });
  const allowances: any[] = Array.isArray(allowancesData)
    ? allowancesData
    : (allowancesData as any)?.items ?? (allowancesData as any)?.data ?? [];
  const excessRate = allowances[0] ?? null;

  const { data, isLoading } = useQuery({
    queryKey: ['excess-baggage', filters],
    queryFn: () => excessBaggageApi.getAll({
      status: filters.status || undefined,
      bookingRef: filters.bookingRef || undefined,
      dateFrom: filters.dateFrom || undefined,
      dateTo: filters.dateTo || undefined,
      page: filters.page,
    }),
  });

  const logMutation = useMutation({
    mutationFn: (data: any) => excessBaggageApi.logCharge(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['excess-baggage'] });
      setLogModal(false);
      setLogForm({ bookingId: '', excessWeightKg: '', collectCash: false });
      setLogError(null);
    },
    onError: (e: any) => setLogError(e?.response?.data?.message || e?.message || 'Failed to log charge'),
  });

  const waiveMutation = useMutation({
    mutationFn: ({ id, reason }: { id: string; reason: string }) =>
      excessBaggageApi.waive(id, { waivedBy: 'supervisor', waivedReason: reason }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['excess-baggage'] });
      setWaiveModal(null);
      setWaiveReason('');
      setWaiveError(null);
    },
    onError: (e: any) => setWaiveError(e?.response?.data?.message || e?.message || 'Failed to waive'),
  });

  const resendMutation = useMutation({
    mutationFn: (id: string) => excessBaggageApi.resendLink(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['excess-baggage'] });
      setResendSuccess(true);
      setResendError(null);
    },
    onError: (e: any) => setResendError(e?.response?.data?.message || e?.message || 'Failed to resend link'),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => excessBaggageApi.delete(id),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['excess-baggage'] }),
  });

  const columns = [
    {
      key: 'booking', label: 'Booking',
      render: (c: any) => (
        <div className="text-sm">
          <div className="font-mono font-semibold">{c.booking?.bookingRef ?? '—'}</div>
          <div className="text-muted-foreground">{formatDateTime(c.createdAt)}</div>
        </div>
      ),
    },
    {
      key: 'weight', label: 'Excess / Charge',
      render: (c: any) => (
        <div className="text-sm">
          <div className="font-semibold">{c.excessWeightKg} kg</div>
          <div className="text-muted-foreground">{formatCurrency(c.feePerKgMinor, c.currency)}/kg</div>
        </div>
      ),
    },
    {
      key: 'total', label: 'Total',
      render: (c: any) => <span className="font-semibold">{formatCurrency(c.totalMinor, c.currency)}</span>,
    },
    {
      key: 'status', label: 'Status',
      render: (c: any) => (
        <Badge variant="status" status={STATUS_VARIANT[c.status] ?? 'PENDING'}>
          {c.status.replace('_', ' ')}
        </Badge>
      ),
    },
    {
      key: 'contact', label: 'Contact',
      render: (c: any) => (
        <div className="text-sm text-muted-foreground">
          {c.contactPhone && <div>{c.contactPhone}</div>}
          {c.contactEmail && <div>{c.contactEmail}</div>}
          {!c.contactPhone && !c.contactEmail && '—'}
        </div>
      ),
    },
    {
      key: 'expires', label: 'Expires',
      render: (c: any) => (
        <span className={`text-sm ${new Date(c.expiresAt) < new Date() && c.status === 'PENDING' ? 'text-red-500' : 'text-muted-foreground'}`}>
          {formatDateTime(c.expiresAt)}
        </span>
      ),
    },
  ];

  const actions = [
    {
      label: 'Resend Link',
      icon: Send,
      variant: 'secondary' as const,
      onClick: (c: any) => { setResendModal(c); setResendSuccess(false); setResendError(null); },
      show: (c: any) => c.status === 'PENDING',
    },
    {
      label: 'Waive',
      icon: RefreshCw,
      variant: 'secondary' as const,
      onClick: (c: any) => { setWaiveModal(c); setWaiveReason(''); setWaiveError(null); },
      show: (c: any) => !['PAID', 'CASH_COLLECTED', 'WAIVED'].includes(c.status),
    },
    {
      label: 'Delete',
      icon: Trash2,
      variant: 'danger' as const,
      onClick: (c: any) => {
        if (confirm('Are you sure you want to delete this charge?')) {
          deleteMutation.mutate(c.id);
        }
      },
      show: (c: any) => ['EXPIRED', 'WAIVED'].includes(c.status),
    },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Excess Lugagge</h1>
          <p className="text-muted-foreground">Track and manage excess luggage charges at boarding</p>
        </div>
        <ActionButton icon={Plus} onClick={() => { setLogModal(true); setLogError(null); setLogForm({ bookingId: '', excessWeightKg: '', collectCash: false }); }}>
          Log Excess Luggage
        </ActionButton>
      </div>

      <div className="card">
        <div className="mb-4 space-y-3">
          <div className="flex flex-wrap gap-3">
            <div className="flex-1 min-w-48">
              <input className="input" placeholder="Search by booking ref…"
                value={filters.bookingRef}
                onChange={(e) => setFilters({ ...filters, bookingRef: e.target.value, page: '1' })} />
            </div>
            <select className="input w-44" value={filters.status}
              onChange={(e) => setFilters({ ...filters, status: e.target.value, page: '1' })}>
              <option value="">All Status</option>
              <option value="PENDING">Pending</option>
              <option value="PAID">Paid</option>
              <option value="CASH_COLLECTED">Cash Collected</option>
              <option value="EXPIRED">Expired</option>
              <option value="WAIVED">Waived</option>
            </select>
            <button type="button" className="input w-auto px-4 text-sm font-medium text-primary border-primary/40"
              onClick={() => setShowExtraFilters(v => !v)}>
              {showExtraFilters ? 'Hide Filters ▲' : 'More Filters ▼'}
            </button>
          </div>
          {showExtraFilters && (
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-1">
              <div>
                <label className="label">Date From</label>
                <input type="date" className="input" value={filters.dateFrom}
                  onChange={(e) => setFilters({ ...filters, dateFrom: e.target.value, page: '1' })} />
              </div>
              <div>
                <label className="label">Date To</label>
                <input type="date" className="input" value={filters.dateTo}
                  onChange={(e) => setFilters({ ...filters, dateTo: e.target.value, page: '1' })} />
              </div>
            </div>
          )}
        </div>
      </div>

      <DataTable
        data={data?.items || []}
        columns={columns}
        actions={actions}
        loading={isLoading}
        emptyMessage="No excess baggage charges found"
      />

      {/* Log Excess Luggage Modal */}
      <Modal isOpen={logModal} onClose={() => setLogModal(false)} title="Log Excess Luggage" size="sm">
        <div className="space-y-4">
          {user && (
            <div className="text-sm text-muted-foreground">
              Logging as agent: <span className="font-semibold text-foreground">{user.fullName}</span>
            </div>
          )}
          {!excessRate ? (
            <div className="rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 p-3 text-sm text-amber-800 dark:text-amber-200">
              No excess luggage rate configured. Please set a rate in Tariff Rates before logging.
            </div>
          ) : (
            <>
              <div className="rounded-lg bg-muted/50 px-3 py-2 text-sm">
                Rate: <span className="font-semibold">{(excessRate.excessFeePerKg / 100).toFixed(2)} ETB/kg</span>
              </div>
              <div>
                <label className="label">Booking ID</label>
                <input
                  className="input"
                  placeholder="Booking UUID"
                  value={logForm.bookingId}
                  onChange={(e) => setLogForm({ ...logForm, bookingId: e.target.value })}
                />
              </div>
              <div>
                <label className="label">Excess Weight (kg)</label>
                <input
                  type="number"
                  min="1"
                  className="input"
                  placeholder="e.g. 5"
                  value={logForm.excessWeightKg}
                  onChange={(e) => setLogForm({ ...logForm, excessWeightKg: e.target.value })}
                />
              </div>
              {logForm.excessWeightKg && (
                <p className="text-xs text-muted-foreground">
                  Estimated charge: <span className="font-semibold">{((excessRate.excessFeePerKg / 100) * parseInt(logForm.excessWeightKg || '0')).toFixed(2)} ETB</span>
                </p>
              )}
              <label className="flex items-center gap-2 text-sm cursor-pointer">
                <input
                  type="checkbox"
                  checked={logForm.collectCash}
                  onChange={(e) => setLogForm({ ...logForm, collectCash: e.target.checked })}
                />
                Collect cash now (no payment link sent)
              </label>
              {!logForm.collectCash && (
                <p className="text-xs text-muted-foreground">
                  A payment link will be sent to the passenger's email and phone on file.
                </p>
              )}
            </>
          )}
          {logError && <p className="text-sm text-red-600 dark:text-red-400">{logError}</p>}
          <div className="flex justify-end gap-2 pt-2">
            <ActionButton variant="secondary" onClick={() => setLogModal(false)}>Cancel</ActionButton>
            {excessRate && (
              <ActionButton
                loading={logMutation.isPending}
                onClick={() => {
                  if (!logForm.bookingId.trim() || !logForm.excessWeightKg) {
                    setLogError('Booking ID and excess weight are required');
                    return;
                  }
                  logMutation.mutate({
                    bookingId: logForm.bookingId.trim(),
                    excessWeightKg: parseInt(logForm.excessWeightKg),
                    collectCash: logForm.collectCash,
                  });
                }}
              >
                {logForm.collectCash ? 'Log & Collect Cash' : 'Log & Send Payment Link'}
              </ActionButton>
            )}
          </div>
        </div>
      </Modal>

      {/* Resend Link Modal */}
      <Modal isOpen={!!resendModal} onClose={() => setResendModal(null)} title="Resend Payment Link" size="sm">
        {resendModal && (
          <div className="space-y-4">
            {resendSuccess ? (
              <div className="rounded-lg bg-green-50 dark:bg-green-900/20 p-4 text-sm text-green-800 dark:text-green-200">
                ✓ Payment link resent successfully. Expiry extended by 20 minutes.
              </div>
            ) : (
              <>
                <p className="text-sm text-muted-foreground">
                  Resend payment link for booking{' '}
                  <span className="font-mono font-semibold text-foreground">{resendModal.booking?.bookingRef}</span>?
                </p>
                <div className="text-sm space-y-1">
                  {resendModal.contactPhone && <div className="text-muted-foreground">📱 {resendModal.contactPhone}</div>}
                  {resendModal.contactEmail && <div className="text-muted-foreground">✉ {resendModal.contactEmail}</div>}
                </div>
                <p className="text-xs text-muted-foreground">Amount: <span className="font-semibold">{formatCurrency(resendModal.totalMinor, resendModal.currency)}</span>. Expiry will be extended by 20 minutes.</p>
                {resendError && <p className="text-sm text-red-600 dark:text-red-400">{resendError}</p>}
              </>
            )}
            <div className="flex justify-end gap-2 pt-2">
              <ActionButton variant="secondary" onClick={() => setResendModal(null)}>Close</ActionButton>
              {!resendSuccess && (
                <ActionButton icon={Send} loading={resendMutation.isPending} onClick={() => resendMutation.mutate(resendModal.id)}>
                  Resend
                </ActionButton>
              )}
            </div>
          </div>
        )}
      </Modal>

      {/* Waive Modal */}
      <Modal
        isOpen={!!waiveModal}
        onClose={() => setWaiveModal(null)}
        title="Waive Charge"
        size="sm"
      >
        {waiveModal && (
          <div className="space-y-4">
            <p className="text-sm text-muted-foreground">
              Waiving charge of{' '}
              <span className="font-semibold text-foreground">
                {formatCurrency(waiveModal.totalMinor, waiveModal.currency)}
              </span>{' '}
              for booking <span className="font-mono font-semibold">{waiveModal.booking?.bookingRef}</span>.
            </p>
            <div>
              <label className="label">Reason (optional)</label>
              <input
                className="input"
                placeholder="e.g. Medical exemption, scale error…"
                value={waiveReason}
                onChange={(e) => setWaiveReason(e.target.value)}
              />
            </div>
            {waiveError && <p className="text-sm text-red-600 dark:text-red-400">{waiveError}</p>}
            <div className="flex justify-end gap-2 pt-2">
              <ActionButton variant="secondary" onClick={() => setWaiveModal(null)}>Cancel</ActionButton>
              <ActionButton
                loading={waiveMutation.isPending}
                onClick={() => waiveMutation.mutate({ id: waiveModal.id, reason: waiveReason })}
              >
                Confirm Waive
              </ActionButton>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}
