'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Plus, Edit, 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 ConfirmDialog from '@/components/ui/ConfirmDialog';
import { apiClient } from '@/lib/api-client';
import { formatDateTime } from '@/lib/utils';

export default function FareManagementPage() {
  const [filters, setFilters] = useState({ scheduleId: '' });
  const [showModal, setShowModal] = useState(false);
  const [editingRule, setEditingRule] = useState<any>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<{ isOpen: boolean; rule: any | null; error?: string }>({ isOpen: false, rule: null });
  const [formError, setFormError] = useState<string | null>(null);
  const queryClient = useQueryClient();

  const { data: fareRules, isLoading } = useQuery<any[]>({
    queryKey: ['fare-rules', filters],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (filters.scheduleId) params.append('scheduleId', filters.scheduleId);
      const res = await apiClient.get<any>(`/schedules/fares?${params}`);
      return Array.isArray(res) ? res : (res as any)?.items || (res as any)?.data || [];
    },
  });

  const { data: schedulesData } = useQuery({
    queryKey: ['schedules'],
    queryFn: () => apiClient.get<any>('/schedules'),
  });

  const { data: seatClassesData } = useQuery({
    queryKey: ['seat-classes'],
    queryFn: () => apiClient.get<any>('/fleet/classes'),
  });

  const schedules = Array.isArray(schedulesData) ? schedulesData : (schedulesData as any)?.items || [];
  const seatClasses = Array.isArray(seatClassesData) ? seatClassesData : (seatClassesData as any)?.items || (seatClassesData as any)?.data || [];

  const createMutation = useMutation({
    mutationFn: (data: any) => apiClient.post('/schedules/fares', data),
    onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['fare-rules'] }); setShowModal(false); setEditingRule(null); setFormError(null); },
    onError: (e: any) => setFormError(e?.response?.data?.message || e?.message || 'Failed to save fare rule'),
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => apiClient.patch(`/schedules/fares/${id}`, data),
    onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['fare-rules'] }); setShowModal(false); setEditingRule(null); setFormError(null); },
    onError: (e: any) => setFormError(e?.response?.data?.message || e?.message || 'Failed to update fare rule'),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => apiClient.delete(`/schedules/fares/${id}`),
    onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['fare-rules'] }); setDeleteConfirm({ isOpen: false, rule: null }); },
    onError: (e: any) => setDeleteConfirm(prev => ({ ...prev, error: e?.response?.data?.message || e?.message || 'Failed to delete' })),
  });

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setFormError(null);
    const fd = new FormData(e.currentTarget);
    const payload: any = {
      seatClassId: fd.get('seatClassId') as string,
      baseFareMinor: Math.round(parseFloat(fd.get('baseFareMinor') as string) * 100),
      validFrom: new Date(fd.get('validFrom') as string).toISOString(),
    };
    const scheduleId = fd.get('scheduleId') as string;
    const nationality = fd.get('nationality') as string;
    const passengerCategory = fd.get('passengerCategory') as string;
    const validUntil = fd.get('validUntil') as string;
    if (scheduleId) payload.scheduleId = scheduleId;
    if (nationality) payload.nationality = nationality;
    if (passengerCategory) payload.passengerCategory = passengerCategory;
    if (validUntil) payload.validUntil = new Date(validUntil).toISOString();

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

  const columns = [
    {
      key: 'seatClass', label: 'Seat Class',
      render: (r: any) => <span className="font-medium">{r.seatClass?.name || r.seatClassId}</span>,
    },
    {
      key: 'schedule', label: 'Schedule',
      render: (r: any) => r.trip
        ? <span className="text-sm">{r.trip.originStation?.name} → {r.trip.destinationStation?.name}<br /><span className="text-xs text-muted-foreground">{r.trip.departureAt ? new Date(r.trip.departureAt).toLocaleDateString() : ''}</span></span>
        : <span className="text-xs text-muted-foreground">All schedules</span>,
    },
    {
      key: 'passengerCategory', label: 'Category',
      render: (r: any) => r.passengerCategory
        ? <Badge variant="status" status={r.passengerCategory === 'ADULT' ? 'CONFIRMED' : 'INFO'}>{r.passengerCategory}</Badge>
        : <span className="text-xs text-muted-foreground">All</span>,
    },
    {
      key: 'nationality', label: 'Nationality',
      render: (r: any) => <span className="text-sm">{r.nationality || 'All'}</span>,
    },
    {
      key: 'baseFareMinor', label: 'Base Fare',
      render: (r: any) => <span className="font-mono">{(r.baseFareMinor / 100).toFixed(2)}</span>,
    },
    {
      key: 'validity', label: 'Validity',
      render: (r: any) => (
        <div className="text-xs">
          <div>From: {formatDateTime(r.validFrom)}</div>
          {r.validUntil && <div>Until: {formatDateTime(r.validUntil)}</div>}
          {!r.validUntil && <div className="text-muted-foreground">No expiry</div>}
        </div>
      ),
    },
  ];

  const actions = [
    {
      label: 'Edit', icon: Edit, variant: 'secondary' as const,
      onClick: (r: any) => { setEditingRule(r); setFormError(null); setShowModal(true); },
    },
    {
      label: 'Delete', icon: Trash2, variant: 'danger' as const,
      onClick: (r: any) => setDeleteConfirm({ isOpen: true, rule: r }),
    },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Fare Management</h1>
          <p className="text-muted-foreground">Configure fare rules by seat class, passenger category, and nationality</p>
        </div>
        <ActionButton icon={Plus} onClick={() => { setEditingRule(null); setFormError(null); setShowModal(true); }}>Add Fare Rule</ActionButton>
      </div>

      <div className="card">
        <div className="flex flex-wrap gap-3 mb-4">
          <select className="input w-64" value={filters.scheduleId}
            onChange={(e) => setFilters({ ...filters, scheduleId: e.target.value })}>
            <option value="">All Schedules</option>
            {schedules.map((s: any) => (
              <option key={s.id} value={s.id}>
                {s.originStation?.name} → {s.destinationStation?.name} ({s.departureAt ? new Date(s.departureAt).toLocaleDateString() : s.id.slice(0, 8)})
              </option>
            ))}
          </select>
        </div>
        <DataTable data={fareRules || []} columns={columns} actions={actions} loading={isLoading} emptyMessage="No fare rules found" />
      </div>

      <ConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, rule: null })}
        onConfirm={() => deleteMutation.mutate(deleteConfirm.rule?.id)}
        title="Delete Fare Rule"
        message={`Delete fare rule for ${deleteConfirm.rule?.seatClass?.name || 'this class'}?`}
        confirmText="Delete" isDanger isLoading={deleteMutation.isPending}
        error={deleteConfirm.error}
      />

      <Modal isOpen={showModal} onClose={() => { setShowModal(false); setEditingRule(null); }}
        title={`${editingRule ? 'Edit' : 'Add'} Fare Rule`} size="lg">
        <form onSubmit={handleSubmit} className="space-y-4">
          {formError && (
            <div className="rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 p-3 text-sm text-red-800 dark:text-red-200">{formError}</div>
          )}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="label">Seat Class *</label>
              <select name="seatClassId" className="input" defaultValue={editingRule?.seatClassId || ''} required>
                <option value="">Select Seat Class</option>
                {seatClasses.map((sc: any) => (
                  <option key={sc.id} value={sc.id}>{sc.name}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="label">Schedule (optional)</label>
              <select name="scheduleId" className="input" defaultValue={editingRule?.tripId || ''}>
                <option value="">All Schedules</option>
                {schedules.map((s: any) => (
                  <option key={s.id} value={s.id}>
                    {s.originStation?.name} → {s.destinationStation?.name} ({s.departureAt ? new Date(s.departureAt).toLocaleDateString() : s.id.slice(0, 8)})
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="label">Passenger Category (optional)</label>
              <select name="passengerCategory" className="input" defaultValue={editingRule?.passengerCategory || ''}>
                <option value="">All Categories</option>
                <option value="ADULT">Adult (≥5 years)</option>
                <option value="CHILD">Child (&lt;5 years)</option>
              </select>
              <p className="text-xs text-muted-foreground mt-1">Leave blank to apply to all passengers</p>
            </div>
            <div>
              <label className="label">Nationality (optional)</label>
              <select name="nationality" className="input" defaultValue={editingRule?.nationality || ''}>
                <option value="">All Nationalities</option>
                <option value="Ethiopian">Ethiopian</option>
                <option value="Djiboutian">Djiboutian</option>
                <option value="Other">Other (International)</option>
              </select>
            </div>
            <div>
              <label className="label">Base Fare *</label>
              <input type="number" name="baseFareMinor" className="input" min="0" step="0.01"
                defaultValue={editingRule ? (editingRule.baseFareMinor / 100).toFixed(2) : ''} required
                placeholder="e.g. 350.00" />
            </div>
            <div>
              <label className="label">Valid From *</label>
              <input type="datetime-local" name="validFrom" className="input" required
                defaultValue={editingRule?.validFrom ? new Date(editingRule.validFrom).toISOString().slice(0, 16) : new Date().toISOString().slice(0, 16)} />
            </div>
            <div>
              <label className="label">Valid Until (optional)</label>
              <input type="datetime-local" name="validUntil" className="input"
                defaultValue={editingRule?.validUntil ? new Date(editingRule.validUntil).toISOString().slice(0, 16) : ''} />
            </div>
          </div>
          <div className="flex justify-end gap-2 pt-4">
            <ActionButton type="button" variant="secondary" onClick={() => { setShowModal(false); setEditingRule(null); }}>Cancel</ActionButton>
            <ActionButton type="submit" loading={createMutation.isPending || updateMutation.isPending}>
              {editingRule ? 'Update' : 'Create'} Fare Rule
            </ActionButton>
          </div>
        </form>
      </Modal>
    </div>
  );
}
