'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { fleetApi } from '@/lib/api';
import DataTable from '@/components/ui/DataTable';
import ActionButton from '@/components/ui/ActionButton';
import Modal from '@/components/ui/Modal';
import { Plus, Search, Grid3x3, Train, Edit, Trash2 } from 'lucide-react';

export default function CoachesPage() {
  const [search, setSearch] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingCoach, setEditingCoach] = useState<any>(null);
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['coaches', search],
    queryFn: () => fleetApi.getCoaches({ search }),
  });

  const createMutation = useMutation({
    mutationFn: fleetApi.createCoach,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['coaches'] });
      setShowModal(false);
      setEditingCoach(null);
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => fleetApi.updateCoach(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['coaches'] });
      setShowModal(false);
      setEditingCoach(null);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: fleetApi.deleteCoach,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['coaches'] });
    },
  });

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const coachData = {
      coachNumber: formData.get('coachNumber') as string,
      label: formData.get('label') as string,
      seatClassId: formData.get('seatClassId') as string,
      coachType: formData.get('coachType') as string,
      mode: formData.get('mode') as string,
      seatArrangement: formData.get('seatArrangement') as string,
      totalUnits: parseInt(formData.get('totalUnits') as string),
      isActive: formData.get('isActive') === 'true',
    };

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

  const handleDelete = async (coach: any) => {
    if (confirm(`Are you sure you want to delete coach ${coach.coachNumber}?`)) {
      await deleteMutation.mutateAsync(coach.id);
    }
  };

  const coaches = data?.items || data?.data || [];

  const columns = [
    {
      key: 'coachNumber',
      label: 'Coach Number',
      sortable: true,
      render: (coach: any) => (
        <div className="flex items-center gap-2">
          <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-[rgb(20,113,76)]">
            <Grid3x3 className="h-4 w-4 text-white" />
          </div>
          <span className="font-medium">{coach.coachNumber}</span>
        </div>
      ),
    },
    {
      key: 'seatClass',
      label: 'Seat Class',
      render: (coach: any) => {
        const seatClass = coach.seatClass?.name || coach.serviceClass || 'N/A';
        const colorMap: Record<string, string> = {
          'ECONOMY_REGULAR': 'edr-badge-info',
          'ECONOMY_BED': 'edr-badge-warning',
          'VIP_BED': 'edr-badge-success',
        };
        return (
          <span className={`edr-badge ${colorMap[seatClass] || 'edr-badge-info'}`}>
            {seatClass.replace(/_/g, ' ')}
          </span>
        );
      },
    },
    {
      key: 'totalSeats',
      label: 'Total Seats',
      render: (coach: any) => (
        <span className="font-mono text-sm">{coach.totalSeats || coach.totalUnits || 0}</span>
      ),
    },
    {
      key: 'layout',
      label: 'Layout',
      render: (coach: any) => (
        <span className="text-sm text-muted-foreground">
          {coach.layout || coach.seatLayout || coach.seatArrangement || 'N/A'}
        </span>
      ),
    },
    {
      key: 'status',
      label: 'Status',
      render: (coach: any) => {
        const status = coach.isActive ? 'ACTIVE' : 'INACTIVE';
        const statusMap: Record<string, string> = {
          ACTIVE: 'edr-badge-success',
          MAINTENANCE: 'edr-badge-warning',
          INACTIVE: 'edr-badge-danger',
        };
        return (
          <span className={`edr-badge ${statusMap[status] || 'edr-badge-info'}`}>
            {status}
          </span>
        );
      },
    },
  ];

  const actions = [
    {
      label: 'Edit',
      onClick: (coach: any) => {
        setEditingCoach(coach);
        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-3xl font-bold text-foreground">Coach Management</h1>
          <p className="text-muted-foreground mt-1">Manage train coaches and configurations</p>
        </div>
        <ActionButton
          icon={Plus}
          onClick={() => {
            setEditingCoach(null);
            setShowModal(true);
          }}
        >
          Add Coach
        </ActionButton>
      </div>

      <div className="card">
        <div className="flex items-center gap-4 mb-6">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <input
              type="text"
              placeholder="Search coaches..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="input pl-10"
            />
          </div>
        </div>

        <DataTable
          columns={columns}
          data={coaches}
          actions={actions}
          loading={isLoading}
        />
      </div>

      {/* Add/Edit Modal */}
      <Modal
        isOpen={showModal}
        onClose={() => {
          setShowModal(false);
          setEditingCoach(null);
        }}
        title={`${editingCoach ? 'Edit' : 'Add'} Coach`}
        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">Coach Number *</label>
              <input
                type="text"
                name="coachNumber"
                className="input"
                defaultValue={editingCoach?.coachNumber}
                required
                placeholder="e.g., C001"
              />
            </div>
            <div>
              <label className="label">Label *</label>
              <input
                type="text"
                name="label"
                className="input"
                defaultValue={editingCoach?.label}
                required
                placeholder="e.g., Coach 1"
              />
            </div>
            <div>
              <label className="label">Coach Type</label>
              <select name="coachType" className="input" defaultValue={editingCoach?.coachType}>
                <option value="passenger">Passenger</option>
                <option value="sleeper">Sleeper</option>
                <option value="dining">Dining</option>
                <option value="baggage">Baggage</option>
              </select>
            </div>
            <div>
              <label className="label">Mode *</label>
              <select name="mode" className="input" defaultValue={editingCoach?.mode || 'seat'}>
                <option value="seat">Seat</option>
                <option value="bed">Bed</option>
                <option value="convertible">Convertible</option>
              </select>
            </div>
            <div>
              <label className="label">Seat Arrangement</label>
              <input
                type="text"
                name="seatArrangement"
                className="input"
                defaultValue={editingCoach?.seatArrangement}
                placeholder="e.g., 2+2"
              />
            </div>
            <div>
              <label className="label">Total Units *</label>
              <input
                type="number"
                name="totalUnits"
                className="input"
                defaultValue={editingCoach?.totalUnits}
                required
                min="1"
                placeholder="60"
              />
            </div>
            <div>
              <label className="label">Status</label>
              <select
                name="isActive"
                className="input"
                defaultValue={editingCoach?.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);
                setEditingCoach(null);
              }}
            >
              Cancel
            </ActionButton>
            <ActionButton
              type="submit"
              loading={createMutation.isPending || updateMutation.isPending}
            >
              {editingCoach ? 'Update' : 'Create'} Coach
            </ActionButton>
          </div>
        </form>
      </Modal>
    </div>
  );
}
