'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Plus, Edit, Trash2, Train } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import ActionButton from '@/components/ui/ActionButton';
import Modal from '@/components/ui/Modal';
import Badge from '@/components/ui/Badge';
import { fleetApi } from '@/lib/api';
import { Train as TrainType } from '@/types';
import { formatDate } from '@/lib/utils';

export default function TrainsPage() {
  const [showModal, setShowModal] = useState(false);
  const [editingTrain, setEditingTrain] = useState<TrainType | null>(null);
  
  const queryClient = useQueryClient();

  const { data: trainsData, isLoading: trainsLoading } = useQuery({
    queryKey: ['trains'],
    queryFn: () => fleetApi.getTrains(),
  });

  const createTrainMutation = useMutation({
    mutationFn: fleetApi.createTrain,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['trains'] });
      setShowModal(false);
      setEditingTrain(null);
    },
  });

  const updateTrainMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => fleetApi.updateTrain(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['trains'] });
      setShowModal(false);
      setEditingTrain(null);
    },
  });

  const handleSubmit = async (formData: FormData) => {
    const trainData = {
      number: formData.get('number') as string,
      name: formData.get('name') as string,
      operatorId: formData.get('operatorId') as string,
      operatorName: formData.get('operatorName') as string,
      description: formData.get('description') as string,
      isActive: formData.get('isActive') === 'true',
    };

    if (editingTrain) {
      await updateTrainMutation.mutateAsync({ id: editingTrain.id, data: trainData });
    } else {
      await createTrainMutation.mutateAsync(trainData);
    }
  };

  const trainColumns = [
    {
      key: 'number',
      label: 'Train Number',
      sortable: true,
      render: (train: TrainType) => (
        <div className="flex items-center gap-2">
          <Train className="h-4 w-4 text-[rgb(20,113,76)]" />
          <span className="font-mono font-semibold">{train.number}</span>
        </div>
      ),
    },
    {
      key: 'name',
      label: 'Train Name',
      sortable: true,
      render: (train: TrainType) => (
        <div>
          <div className="font-medium">{train.name}</div>
          <div className="text-sm text-gray-500">{train.description}</div>
        </div>
      ),
    },
    {
      key: 'operatorName',
      label: 'Operator',
      render: (train: TrainType) => (
        <span>{train.operatorName || train.operatorId}</span>
      ),
    },
    {
      key: 'isActive',
      label: 'Status',
      render: (train: TrainType) => (
        <Badge variant="status" status={train.isActive ? 'CONFIRMED' : 'CANCELLED'}>
          {train.isActive ? 'Active' : 'Inactive'}
        </Badge>
      ),
    },
    {
      key: 'createdAt',
      label: 'Created',
      render: (train: TrainType) => formatDate(train.createdAt),
    },
  ];

  const actions = [
    {
      label: 'Edit',
      onClick: (train: TrainType) => {
        setEditingTrain(train);
        setShowModal(true);
      },
      variant: 'secondary' as const,
      icon: Edit,
    },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Train Management</h1>
          <p className="text-gray-600 dark:text-gray-400">Manage trains in the system</p>
        </div>
        <ActionButton
          onClick={() => {
            setEditingTrain(null);
            setShowModal(true);
          }}
          icon={Plus}
        >
          Add Train
        </ActionButton>
      </div>

      {/* Trains Table */}
      <DataTable
        data={trainsData?.items || []}
        columns={trainColumns}
        actions={actions}
        loading={trainsLoading}
        emptyMessage="No trains found"
      />

      {/* Add/Edit Modal */}
      <Modal
        isOpen={showModal}
        onClose={() => {
          setShowModal(false);
          setEditingTrain(null);
        }}
        title={`${editingTrain ? 'Edit' : 'Add'} Train`}
        size="lg"
      >
        <form
          onSubmit={async (e) => {
            e.preventDefault();
            const formData = new FormData(e.currentTarget);
            await handleSubmit(formData);
          }}
          className="space-y-4"
        >
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="label">Train Number *</label>
              <input
                type="text"
                name="number"
                className="input"
                defaultValue={editingTrain?.number}
                required
                placeholder="e.g., EDR-001"
              />
            </div>
            <div>
              <label className="label">Train Name *</label>
              <input
                type="text"
                name="name"
                className="input"
                defaultValue={editingTrain?.name}
                required
                placeholder="e.g., Express Service"
              />
            </div>
            <div>
              <label className="label">Operator ID</label>
              <input
                type="text"
                name="operatorId"
                className="input"
                defaultValue={editingTrain?.operatorId || 'op_edr'}
                placeholder="op_edr"
              />
            </div>
            <div>
              <label className="label">Operator Name</label>
              <input
                type="text"
                name="operatorName"
                className="input"
                defaultValue={editingTrain?.operatorName}
                placeholder="Ethio-Djibouti Railway"
              />
            </div>
            <div className="md:col-span-2">
              <label className="label">Description</label>
              <textarea
                name="description"
                className="input"
                rows={3}
                defaultValue={editingTrain?.description}
                placeholder="Train description..."
              />
            </div>
            <div>
              <label className="label">Status</label>
              <select
                name="isActive"
                className="input"
                defaultValue={editingTrain?.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);
                setEditingTrain(null);
              }}
            >
              Cancel
            </ActionButton>
            <ActionButton
              type="submit"
              loading={createTrainMutation.isPending || updateTrainMutation.isPending}
            >
              {editingTrain ? 'Update' : 'Create'} Train
            </ActionButton>
          </div>
        </form>
      </Modal>
    </div>
  );
}
