'use client';

import { useState } from 'react';
import { Edit, Trash2 } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Modal from '@/components/ui/Modal';
import ActionButton from '@/components/ui/ActionButton';
import ConfirmDialog from '@/components/ui/ConfirmDialog';
import { useBaggageMutations } from './hooks';
import type { SeatClass, BaggageAllowance } from './types';

interface Props {
  allClasses: SeatClass[];
  isOpen: boolean;
  onClose: () => void;
}

export default function BaggageTab({ allClasses, isOpen, onClose }: Props) {
  const { allowances, isLoading, create, update, remove } = useBaggageMutations();
  const [form, setForm] = useState({ seatClassId: '', maxWeightKg: '', maxPiecesCount: '', excessFeePerKg: '' });
  const [editing, setEditing] = useState<BaggageAllowance | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<{ isOpen: boolean; id: string | null }>({ isOpen: false, id: null });

  const resetForm = () => { setForm({ seatClassId: '', maxWeightKg: '', maxPiecesCount: '', excessFeePerKg: '' }); setEditing(null); setError(null); };

  const handleSave = async () => {
    setError(null);
    if (!form.excessFeePerKg) {
      setError('Excess fee per kg is required'); return;
    }
    const feeMinor = Math.round(parseFloat(form.excessFeePerKg) * 100);
    try {
      if (editing) {
        await update.mutateAsync({ id: editing.id, excessFeePerKg: feeMinor });
      } else {
        // Create a rule for every seat class that doesn't already have one
        const existingClassIds = new Set(allowances.map((a: BaggageAllowance) => a.seatClassId));
        const missing = allClasses.filter(sc => !existingClassIds.has(sc.id));
        if (!missing.length) { setError('All seat classes already have a rule. Use Edit to update.'); return; }
        await Promise.all(missing.map(sc => create.mutateAsync({ seatClassId: sc.id, excessFeePerKg: feeMinor })));
      }
      resetForm();
      onClose();
    } catch (e: any) {
      setError(e?.response?.data?.message ?? 'Failed to save');
    }
  };

  return (
    <>
      {isLoading ? (
        <div className="flex items-center justify-center py-8">
          <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
        </div>
      ) : (
        <DataTable
          data={allowances}
          columns={[
            { key: 'excessFeePerKg', label: 'Fare per kg (ETB)', render: (a: BaggageAllowance) => <span className="font-mono font-semibold">{(a.excessFeePerKg / 100).toFixed(2)} ETB</span> },
          ]}
          actions={[
            {
              label: 'Edit', icon: Edit, variant: 'secondary' as const,
              onClick: (a: BaggageAllowance) => {
                setEditing(a);
                setForm({ seatClassId: a.seatClassId, maxWeightKg: String(a.maxWeightKg), maxPiecesCount: String(a.maxPiecesCount), excessFeePerKg: (a.excessFeePerKg / 100).toFixed(2) });
                setError(null);
              },
            },
            { label: 'Delete', icon: Trash2, variant: 'danger' as const, onClick: (a: BaggageAllowance) => setDeleteConfirm({ isOpen: true, id: a.id }) },
          ]}
          loading={false}
          emptyMessage='No excess luggage tariff rates defined. Click "Add Luggage Rate" to create one.'
        />
      )}

      <Modal
        isOpen={isOpen || !!editing}
        onClose={() => { resetForm(); onClose(); }}
        title={editing ? 'Edit Excess Luggage Rate' : 'Add Excess Luggage Rate'}
        size="md"
      >
        <div className="space-y-4">
          {error && <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 p-3 rounded-lg text-sm text-red-800 dark:text-red-200">{error}</div>}
          <div>
            <label className="label">Excess Fee per kg (ETB) *</label>
            <input type="number" min="0" step="0.01" className="input w-full" placeholder="e.g. 50.00" value={form.excessFeePerKg} onChange={e => setForm({ ...form, excessFeePerKg: e.target.value })} />
            <p className="text-xs text-muted-foreground mt-1">Amount charged per kg above the free allowance</p>
          </div>
          <div className="flex justify-end gap-2 pt-2">
            <ActionButton variant="secondary" onClick={() => { resetForm(); onClose(); }}>Cancel</ActionButton>
            <ActionButton onClick={handleSave} loading={create.isPending || update.isPending}>
              {editing ? 'Update' : 'Save'}
            </ActionButton>
          </div>
        </div>
      </Modal>

      <ConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, id: null })}
        onConfirm={() => remove.mutate(deleteConfirm.id!, { onSuccess: () => setDeleteConfirm({ isOpen: false, id: null }) })}
        title="Delete Allowance Rule"
        message="Are you sure you want to delete this baggage allowance rule?"
        confirmText="Delete"
        isDanger
        isLoading={remove.isPending}
        warning="The excess baggage fallback rate (50 ETB/kg) will apply until a new rule is created."
      />
    </>
  );
}
