'use client';

import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Plus, Loader2, Zap, Trash2, Edit, Search, X } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import ActionButton from '@/components/ui/ActionButton';
import Modal from '@/components/ui/Modal';
import ConfirmDialog from '@/components/ui/ConfirmDialog';
import { apiClient } from '@/lib/api-client';

interface Schedule {
  id: string;
  trainId: string;
  routeId: string;
  departureAt: string;
  arrivalAt: string;
  status: string;
  stopsCount: number;
  train?: { id: string; name: string; number: string };
  originStation?: { id: string; name: string };
  destinationStation?: { id: string; name: string };
  coachAssignments?: Array<{ coachId: string; positionNumber: number; coach?: { id: string; number: string } }>;
}

interface Train {
  id: string;
  name: string;
  number: string;
}

interface Route {
  id: string;
  name: string;
  code: string;
}

interface Coach {
  id: string;
  number: string;
  coachNumber?: string;
  capacity: number;
  sequence?: number;
  coachType?: { name: string };
}

export default function SchedulesPage() {
  const [showModal, setShowModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [editingSchedule, setEditingSchedule] = useState<Schedule | null>(null);
  const [selectedSchedules, setSelectedSchedules] = useState<Set<string>>(new Set());
  const [deleteConfirm, setDeleteConfirm] = useState<{ isOpen: boolean; item: any | null; isBulk?: boolean }>(
    { isOpen: false, item: null }
  );
  const [error, setError] = useState<string | null>(null);
  const queryClient = useQueryClient();

  const [bulkForm, setBulkForm] = useState({
    trainId: '',
    routeId: '',
    startDateTime: '',
    durationHours: '12',
    repeatEveryDays: '1',
    forNextDays: '30',
    coachIds: [] as string[],
  });

  const [editForm, setEditForm] = useState({
    departureAt: '',
    arrivalAt: '',
    status: 'SCHEDULED',
    coachIds: [] as string[],
  });

  const [filters, setFilters] = useState({
    search: '',
    trainId: '',
    routeId: '',
    date: '',
  });

  const { data: schedulesData, isLoading: schedulesLoading } = useQuery({
    queryKey: ['schedules', filters],
    queryFn: () => {
      const params = new URLSearchParams();
      if (filters.trainId) params.append('trainId', filters.trainId);
      if (filters.routeId) params.append('routeId', filters.routeId);
      if (filters.date) params.append('date', filters.date);
      return apiClient.get<Schedule[]>(`/schedules?${params.toString()}`);
    },
    retry: 1,
  });

  const { data: trainsData } = useQuery({
    queryKey: ['trains'],
    queryFn: () => apiClient.get<Train[]>('/fleet/trains'),
    retry: 1,
  });

  const { data: routesData } = useQuery({
    queryKey: ['routes'],
    queryFn: () => apiClient.get<Route[]>('/routes'),
    retry: 1,
  });

  const { data: coachesData } = useQuery({
    queryKey: ['coaches'],
    queryFn: () => apiClient.get<Coach[]>('/fleet/coaches'),
    retry: 1,
  });

  const bulkGenerateMutation = useMutation({
    mutationFn: (data: any) => apiClient.post('/schedules/bulk-generate', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['schedules'] });
      setShowModal(false);
      setBulkForm({
        trainId: '',
        routeId: '',
        startDateTime: '',
        durationHours: '12',
        repeatEveryDays: '1',
        forNextDays: '30',
        coachIds: [],
      });
      setError(null);
    },
    onError: (err: any) => {
      setError(err.response?.data?.message || 'Failed to generate schedules');
    },
  });

  const updateScheduleMutation = useMutation({
    mutationFn: (data: { id: string; payload: any }) =>
      apiClient.patch(`/schedules/${data.id}`, data.payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['schedules'] });
      setShowEditModal(false);
      setEditingSchedule(null);
      setError(null);
    },
    onError: (err: any) => {
      setError(err.response?.data?.message || 'Failed to update schedule');
    },
  });

  const deleteScheduleMutation = useMutation({
    mutationFn: (id: string) => apiClient.delete(`/schedules/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['schedules'] });
    },
  });

  const bulkDeleteMutation = useMutation({
    mutationFn: async (ids: string[]) => {
      await Promise.all(ids.map(id => apiClient.delete(`/schedules/${id}`)));
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['schedules'] });
      setSelectedSchedules(new Set());
    },
  });

  const handleBulkSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);

    if (!bulkForm.trainId || !bulkForm.routeId || !bulkForm.startDateTime) {
      setError('Train, route, and start date/time are required');
      return;
    }

    const payload: any = {
      trainId: bulkForm.trainId,
      routeId: bulkForm.routeId,
      startDateTime: bulkForm.startDateTime,
      durationHours: parseInt(bulkForm.durationHours),
      repeatEveryDays: parseInt(bulkForm.repeatEveryDays),
      forNextDays: parseInt(bulkForm.forNextDays),
    };

    if (bulkForm.coachIds.length > 0) {
      payload.coachIds = bulkForm.coachIds;
    }

    await bulkGenerateMutation.mutateAsync(payload);
  };

  const handleEditSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);

    if (!editingSchedule) return;

    const depDate = new Date(editForm.departureAt);
    const arrDate = new Date(editForm.arrivalAt);

    if (arrDate <= depDate) {
      setError('Arrival time must be after departure time');
      return;
    }

    const payload: any = {
      departureAt: editForm.departureAt,
      arrivalAt: editForm.arrivalAt,
      status: editForm.status,
      coaches: editForm.coachIds.map((coachId: string, idx: number) => ({
        coachId,
        positionNumber: idx + 1,
      })),
    };

    await updateScheduleMutation.mutateAsync({
      id: editingSchedule.id,
      payload,
    });
  };

  const handleDelete = (item: Schedule) => {
    setDeleteConfirm({ isOpen: true, item, isBulk: false });
  };

  const handleBulkDelete = () => {
    if (selectedSchedules.size === 0) return;
    setDeleteConfirm({ isOpen: true, item: Array.from(selectedSchedules), isBulk: true });
  };

  const confirmDelete = async () => {
    if (deleteConfirm.isBulk) {
      const ids = deleteConfirm.item as string[];
      await bulkDeleteMutation.mutateAsync(ids);
    } else if (deleteConfirm.item) {
      await deleteScheduleMutation.mutateAsync(deleteConfirm.item.id);
    }
    setDeleteConfirm({ isOpen: false, item: null });
  };

  const handleEditClick = (schedule: Schedule) => {
    setEditingSchedule(schedule);

    const dep = new Date(schedule.departureAt);
    const arr = new Date(schedule.arrivalAt);

    const depLocal = new Date(dep.getTime() - dep.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
    const arrLocal = new Date(arr.getTime() - arr.getTimezoneOffset() * 60000).toISOString().slice(0, 16);

    setEditForm({
      departureAt: depLocal,
      arrivalAt: arrLocal,
      status: schedule.status,
      coachIds: schedule.coachAssignments?.map((ca: any) => ca.coachId) || [],
    });
    setError(null);
    setShowEditModal(true);
  };

  const schedules = Array.isArray(schedulesData) ? schedulesData : (schedulesData as any)?.items || [];
  const trains = Array.isArray(trainsData) ? trainsData : (trainsData as any)?.items || [];
  const routes = Array.isArray(routesData) ? routesData : (routesData as any)?.items || [];
  const coaches = Array.isArray(coachesData) ? coachesData : (coachesData as any)?.items || [];

  const filteredSchedules = schedules.filter((schedule: Schedule) => {
    if (!filters.search) return true;
    const search = filters.search.toLowerCase();
    return (
      schedule.train?.name.toLowerCase().includes(search) ||
      schedule.train?.number.toLowerCase().includes(search) ||
      schedule.originStation?.name.toLowerCase().includes(search) ||
      schedule.destinationStation?.name.toLowerCase().includes(search) ||
      schedule.status.toLowerCase().includes(search)
    );
  });

  const statusMap: Record<string, string> = {
    SCHEDULED: 'edr-badge-info',
    BOARDING: 'edr-badge-warning',
    EN_ROUTE: 'edr-badge-success',
    ARRIVED: 'edr-badge-secondary',
    CANCELLED: 'edr-badge-danger',
  };

  const scheduleColumns = [
    {
      key: 'checkbox',
      label: (
        <input
          type="checkbox"
          checked={selectedSchedules.size === filteredSchedules.length && filteredSchedules.length > 0}
          onChange={(e) => {
            if (e.target.checked) {
              setSelectedSchedules(new Set(filteredSchedules.map((s: Schedule) => s.id)));
            } else {
              setSelectedSchedules(new Set());
            }
          }}
          className="rounded"
        />
      ),
      render: (schedule: Schedule) => (
        <input
          type="checkbox"
          checked={selectedSchedules.has(schedule.id)}
          onChange={(e) => {
            const newSelected = new Set(selectedSchedules);
            if (e.target.checked) {
              newSelected.add(schedule.id);
            } else {
              newSelected.delete(schedule.id);
            }
            setSelectedSchedules(newSelected);
          }}
          className="rounded"
        />
      ),
    },
    {
      key: 'train.name',
      label: 'Train',
      sortable: true,
      render: (schedule: Schedule) => (
        <div className="font-medium font-mono">
          {schedule.train?.number}
        </div>
      ),
    },
    {
      key: 'route',
      label: 'Route',
      sortable: true,
      render: (schedule: Schedule) => (
        <div className="flex items-center gap-2">
          <span className="text-sm font-medium">
            {schedule.originStation?.name || 'Unknown'}
          </span>
          <span className="text-muted-foreground">→</span>
          <span className="text-sm font-medium">
            {schedule.destinationStation?.name || 'Unknown'}
          </span>
        </div>
      ),
    },
    {
      key: 'departureAt',
      label: 'Departure',
      sortable: true,
      render: (schedule: Schedule) => (
        <span className="font-mono text-sm">{new Date(schedule.departureAt).toLocaleString()}</span>
      ),
    },
    {
      key: 'arrivalAt',
      label: 'Arrival',
      sortable: true,
      render: (schedule: Schedule) => (
        <span className="font-mono text-sm">{new Date(schedule.arrivalAt).toLocaleString()}</span>
      ),
    },
    {
      key: 'coachAssignments',
      label: 'Coaches',
      render: (schedule: Schedule) => (
        <span className="text-sm font-medium">
          {schedule.coachAssignments?.length || 0}
        </span>
      ),
    },
    {
      key: 'status',
      label: 'Status',
      render: (schedule: Schedule) => (
        <span className={`edr-badge ${statusMap[schedule.status] || 'edr-badge-info'}`}>
          {schedule.status}
        </span>
      ),
    },
  ] as any;

  const scheduleActions = [
    {
      label: 'Edit',
      onClick: handleEditClick,
      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">Schedule Management</h1>
          <p className="text-muted-foreground mt-1">Create and manage train schedules</p>
        </div>
        <div className="flex gap-2">
          {selectedSchedules.size > 0 && (
            <ActionButton
              onClick={handleBulkDelete}
              variant="danger"
              loading={bulkDeleteMutation.isPending}
            >
              Delete {selectedSchedules.size} Schedule{selectedSchedules.size !== 1 ? 's' : ''}
            </ActionButton>
          )}
          <ActionButton
            icon={Zap}
            onClick={() => {
              setError(null);
              setShowModal(true);
            }}
          >
            Bulk Generate
          </ActionButton>
        </div>
      </div>

      <div className="card">
        <div className="mb-6 p-4 border-b border-border">
          <div className="space-y-4">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <input
                type="text"
                placeholder="Search by train name, number, station, or status..."
                value={filters.search}
                onChange={(e) => setFilters({ ...filters, search: e.target.value })}
                className="input pl-10 w-full"
              />
            </div>

            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div>
                <label className="label text-sm">Train</label>
                <select
                  value={filters.trainId}
                  onChange={(e) => setFilters({ ...filters, trainId: e.target.value })}
                  className="input"
                >
                  <option value="">All Trains</option>
                  {trains.map((train: Train) => (
                    <option key={train.id} value={train.id}>
                      {train.name} ({train.number})
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="label text-sm">Route</label>
                <select
                  value={filters.routeId}
                  onChange={(e) => setFilters({ ...filters, routeId: e.target.value })}
                  className="input"
                >
                  <option value="">All Routes</option>
                  {routes.map((route: Route) => (
                    <option key={route.id} value={route.id}>
                      {route.name} ({route.code})
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="label text-sm">Date</label>
                <input
                  type="date"
                  value={filters.date}
                  onChange={(e) => setFilters({ ...filters, date: e.target.value })}
                  className="input"
                />
              </div>

              <div className="flex items-end">
                <ActionButton
                  variant="secondary"
                  onClick={() => setFilters({ search: '', trainId: '', routeId: '', date: '' })}
                >
                  Clear Filters
                </ActionButton>
              </div>
            </div>
          </div>
        </div>

        <div className="pt-6">
          {schedulesLoading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-6 w-6 animate-spin" />
            </div>
          ) : filteredSchedules.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              No schedules found. {filters.search && 'Try adjusting your search.'}
            </div>
          ) : (
            <DataTable
              columns={scheduleColumns}
              data={filteredSchedules}
              actions={scheduleActions}
              loading={false}
              emptyMessage="No schedules found."
            />
          )}
        </div>
      </div>

      <ConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, item: null })}
        onConfirm={confirmDelete}
        title={deleteConfirm.isBulk ? 'Delete Multiple Schedules' : 'Delete Schedule'}
        message={
          deleteConfirm.isBulk
            ? `Are you sure you want to delete ${Array.isArray(deleteConfirm.item) ? deleteConfirm.item.length : 0} schedule(s)? This action cannot be undone.`
            : `Are you sure you want to delete this schedule departing on ${
                deleteConfirm.item ? new Date(deleteConfirm.item.departureAt).toLocaleString() : ''
              }?`
        }
        confirmText="Delete"
        isDanger={true}
        warning="This schedule may have bookings. Deleting it may impact these systems."
      />

      <Modal
        isOpen={showModal}
        onClose={() => {
          setShowModal(false);
          setError(null);
          setBulkForm({
            trainId: '',
            routeId: '',
            startDateTime: '',
            durationHours: '12',
            repeatEveryDays: '1',
            forNextDays: '30',
            coachIds: [],
          });
        }}
        title="Bulk Generate Schedules"
        size="lg"
      >
        <form onSubmit={handleBulkSubmit} className="space-y-4">
          {error && (
            <div className="bg-red-50 p-3 rounded-lg text-sm text-red-800">
              {error}
            </div>
          )}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="label">Train *</label>
              <select
                value={bulkForm.trainId}
                onChange={(e) => setBulkForm({ ...bulkForm, trainId: e.target.value })}
                className="input"
                required
              >
                <option value="">Select Train</option>
                {trains.map((train: Train) => (
                  <option key={train.id} value={train.id}>
                    {train.name} ({train.number})
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="label">Route *</label>
              <select
                value={bulkForm.routeId}
                onChange={(e) => setBulkForm({ ...bulkForm, routeId: e.target.value })}
                className="input"
                required
              >
                <option value="">Select Route</option>
                {routes.map((route: Route) => (
                  <option key={route.id} value={route.id}>
                    {route.name} ({route.code})
                  </option>
                ))}
              </select>
            </div>
          </div>

          <div>
            <label className="label">Start Date & Time *</label>
            <input
              type="datetime-local"
              value={bulkForm.startDateTime}
              onChange={(e) => setBulkForm({ ...bulkForm, startDateTime: e.target.value })}
              className="input"
              required
            />
          </div>

          <div className="grid grid-cols-3 gap-4">
            <div>
              <label className="label">Duration (Hours)</label>
              <input
                type="number"
                min="1"
                value={bulkForm.durationHours}
                onChange={(e) => setBulkForm({ ...bulkForm, durationHours: e.target.value })}
                className="input"
              />
            </div>

            <div>
              <label className="label">Repeat Every (Days)</label>
              <input
                type="number"
                min="1"
                value={bulkForm.repeatEveryDays}
                onChange={(e) => setBulkForm({ ...bulkForm, repeatEveryDays: e.target.value })}
                className="input"
              />
            </div>

            <div>
              <label className="label">For Next (Days)</label>
              <input
                type="number"
                min="1"
                value={bulkForm.forNextDays}
                onChange={(e) => setBulkForm({ ...bulkForm, forNextDays: e.target.value })}
                className="input"
              />
            </div>
          </div>

          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="label">Coaches (Optional)</label>
              <button
                type="button"
                onClick={() => {
                  if (bulkForm.coachIds.length === coaches.length) {
                    setBulkForm({ ...bulkForm, coachIds: [] });
                  } else {
                    setBulkForm({ ...bulkForm, coachIds: coaches.map((c: Coach) => c.id) });
                  }
                }}
                className="text-xs text-primary hover:underline"
              >
                {bulkForm.coachIds.length === coaches.length ? 'Deselect All' : 'Select All'}
              </button>
            </div>
            <div className="border border-border rounded-lg p-3 max-h-64 overflow-y-auto space-y-2">
              {coaches.length === 0 ? (
                <p className="text-sm text-muted-foreground">No coaches available</p>
              ) : (
                coaches.map((coach: Coach) => (
                  <label key={coach.id} className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={bulkForm.coachIds.includes(coach.id)}
                      onChange={(e) => {
                        if (e.target.checked) {
                          setBulkForm({
                            ...bulkForm,
                            coachIds: [...bulkForm.coachIds, coach.id],
                          });
                        } else {
                          setBulkForm({
                            ...bulkForm,
                            coachIds: bulkForm.coachIds.filter((id) => id !== coach.id),
                          });
                        }
                      }}
                      className="rounded"
                    />
                    <span className="text-sm">
                      Seq {coach.sequence || 'N/A'} - {coach.number || coach.coachNumber} - {coach.coachType?.name} (Cap: {coach.capacity})
                    </span>
                  </label>
                ))
              )}
            </div>
          </div>

          <div className="bg-blue-50 p-4 rounded-lg">
            <p className="text-sm text-blue-900">
              <strong>Preview:</strong> Will create approximately{' '}
              <strong>{Math.ceil(parseInt(bulkForm.forNextDays) / parseInt(bulkForm.repeatEveryDays))}</strong>{' '}
              schedules, starting from the specified date, repeating every{' '}
              <strong>{bulkForm.repeatEveryDays}</strong> days for the next{' '}
              <strong>{bulkForm.forNextDays}</strong> days.
              {bulkForm.coachIds.length > 0 && (
                <>
                  {' '}
                  Each schedule will have <strong>{bulkForm.coachIds.length}</strong> coach(es) assigned.
                </>
              )}
            </p>
          </div>

          <div className="flex justify-end gap-2 pt-4">
            <ActionButton
              type="button"
              variant="secondary"
              onClick={() => {
                setShowModal(false);
                setError(null);
                setBulkForm({
                  trainId: '',
                  routeId: '',
                  startDateTime: '',
                  durationHours: '12',
                  repeatEveryDays: '1',
                  forNextDays: '30',
                  coachIds: [],
                });
              }}
            >
              Cancel
            </ActionButton>
            <ActionButton type="submit" loading={bulkGenerateMutation.isPending}>
              Generate Schedules
            </ActionButton>
          </div>
        </form>
      </Modal>

      <Modal
        isOpen={showEditModal}
        onClose={() => {
          setShowEditModal(false);
          setEditingSchedule(null);
          setError(null);
        }}
        title={`Edit Schedule - ${editingSchedule?.train?.name} (${editingSchedule?.train?.number})`}
        size="lg"
      >
        {editingSchedule && (
          <form onSubmit={handleEditSubmit} className="space-y-4">
            {error && (
              <div className="bg-red-50 p-3 rounded-lg text-sm text-red-800">
                {error}
              </div>
            )}

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="label">Departure Date & Time *</label>
                <input
                  type="datetime-local"
                  value={editForm.departureAt}
                  onChange={(e) => setEditForm({ ...editForm, departureAt: e.target.value })}
                  className="input"
                  required
                />
              </div>

              <div>
                <label className="label">Arrival Date & Time *</label>
                <input
                  type="datetime-local"
                  value={editForm.arrivalAt}
                  onChange={(e) => setEditForm({ ...editForm, arrivalAt: e.target.value })}
                  className="input"
                  required
                />
              </div>
            </div>

            <div>
              <label className="label">Status</label>
              <select
                value={editForm.status}
                onChange={(e) => setEditForm({ ...editForm, status: e.target.value })}
                className="input"
              >
                <option value="SCHEDULED">Scheduled</option>
                <option value="BOARDING">Boarding</option>
                <option value="EN_ROUTE">En Route</option>
                <option value="ARRIVED">Arrived</option>
                <option value="CANCELLED">Cancelled</option>
              </select>
            </div>

            <div>
              <div className="flex items-center justify-between mb-2">
                <label className="label">Coaches (Optional)</label>
                <button
                  type="button"
                  onClick={() => {
                    if (editForm.coachIds.length === coaches.length) {
                      setEditForm({ ...editForm, coachIds: [] });
                    } else {
                      setEditForm({ ...editForm, coachIds: coaches.map((c: Coach) => c.id) });
                    }
                  }}
                  className="text-xs text-primary hover:underline"
                >
                  {editForm.coachIds.length === coaches.length ? 'Deselect All' : 'Select All'}
                </button>
              </div>
              <div className="border border-border rounded-lg p-3 max-h-64 overflow-y-auto space-y-2">
                {coaches.length === 0 ? (
                  <p className="text-sm text-muted-foreground">No coaches available</p>
                ) : (
                  coaches.map((coach: Coach) => (
                    <label key={coach.id} className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={editForm.coachIds.includes(coach.id)}
                        onChange={(e) => {
                          if (e.target.checked) {
                            setEditForm({
                              ...editForm,
                              coachIds: [...editForm.coachIds, coach.id],
                            });
                          } else {
                            setEditForm({
                              ...editForm,
                              coachIds: editForm.coachIds.filter((id) => id !== coach.id),
                            });
                          }
                        }}
                        className="rounded"
                      />
                      <span className="text-sm">
                        Seq {coach.sequence || 'N/A'} - {coach.number || coach.coachNumber} - {coach.coachType?.name} (Cap: {coach.capacity})
                      </span>
                    </label>
                  ))
                )}
              </div>
            </div>

            <div className="flex justify-end gap-2 pt-4">
              <ActionButton
                type="button"
                variant="secondary"
                onClick={() => {
                  setShowEditModal(false);
                  setEditingSchedule(null);
                  setError(null);
                }}
              >
                Cancel
              </ActionButton>
              <ActionButton type="submit" loading={updateScheduleMutation.isPending}>
                Update Schedule
              </ActionButton>
            </div>
          </form>
        )}
      </Modal>
    </div>
  );
}
