import type { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Form, useActionData, useLoaderData, useNavigation, useSearchParams } from "@remix-run/react";
import { requireAuthLevel } from "~/utils/auth.server";
import DashboardLayout from "~/components/DashboardLayout";
import { useState, useEffect } from "react";
import { prisma } from "~/utils/db.server";
import Toast from "~/components/Toast";

export const meta: MetaFunction = () => [{ title: "Workers - Alhaffer Report System" }];

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const user = await requireAuthLevel(request, 2); // Only supervisors and admins

  const workers = await prisma.worker.findMany({
    orderBy: { name: 'asc' }
  });

  return json({ user, workers });
};

export const action = async ({ request }: ActionFunctionArgs) => {
  await requireAuthLevel(request, 2);

  const formData = await request.formData();
  const intent = formData.get("intent");

  if (intent === "create") {
    const name = formData.get("name");

    if (typeof name !== "string" || !name) {
      return json({ errors: { name: "Name is required" } }, { status: 400 });
    }

    try {
      await prisma.worker.create({
        data: { name, status: "active" }
      });
      return redirect("/workers?success=Worker created successfully!");
    } catch (error: any) {
      if (error.code === "P2002") {
        return json({ errors: { name: "A worker with this name already exists" } }, { status: 400 });
      }
      return json({ errors: { form: "Failed to create worker" } }, { status: 400 });
    }
  }

  if (intent === "update") {
    const id = formData.get("id");
    const name = formData.get("name");
    const status = formData.get("status");

    if (typeof id !== "string" || !id) {
      return json({ errors: { form: "Invalid worker ID" } }, { status: 400 });
    }
    if (typeof name !== "string" || !name) {
      return json({ errors: { name: "Name is required" } }, { status: 400 });
    }
    if (typeof status !== "string" || !["active", "inactive"].includes(status)) {
      return json({ errors: { status: "Valid status is required" } }, { status: 400 });
    }

    try {
      await prisma.worker.update({
        where: { id: parseInt(id) },
        data: { name, status }
      });
      return redirect("/workers?success=Worker updated successfully!");
    } catch (error: any) {
      if (error.code === "P2002") {
        return json({ errors: { name: "A worker with this name already exists" } }, { status: 400 });
      }
      return json({ errors: { form: "Failed to update worker" } }, { status: 400 });
    }
  }

  if (intent === "delete") {
    const id = formData.get("id");

    if (typeof id !== "string" || !id) {
      return json({ errors: { form: "Invalid worker ID" } }, { status: 400 });
    }

    try {
      await prisma.worker.delete({
        where: { id: parseInt(id) }
      });
      return redirect("/workers?success=Worker deleted successfully!");
    } catch (error: any) {
      if (error.code === "P2003") {
        return redirect("/workers?error=Cannot delete worker: worker is assigned to shifts");
      }
      return redirect("/workers?error=Failed to delete worker");
    }
  }

  return json({ errors: { form: "Invalid action" } }, { status: 400 });
};

export default function Workers() {
  const { user, workers } = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();
  const navigation = useNavigation();
  const [searchParams, setSearchParams] = useSearchParams();

  const [showModal, setShowModal] = useState(false);
  const [editingWorker, setEditingWorker] = useState<any>(null);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<number | null>(null);
  const [toast, setToast] = useState<{ message: string; type: "success" | "error" } | null>(null);
  const [showShiftsModal, setShowShiftsModal] = useState(false);
  const [selectedWorker, setSelectedWorker] = useState<any>(null);
  const [workerShifts, setWorkerShifts] = useState<any[]>([]);
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [isLoadingShifts, setIsLoadingShifts] = useState(false);

  const isSubmitting = navigation.state === "submitting";

  // Handle success messages from URL params
  useEffect(() => {
    const successMessage = searchParams.get("success");
    const errorMessage = searchParams.get("error");
    
    if (successMessage) {
      setToast({ message: successMessage, type: "success" });
      setSearchParams({}, { replace: true });
      // Close modals on success
      setShowModal(false);
      setEditingWorker(null);
      setShowDeleteConfirm(null);
    } else if (errorMessage) {
      setToast({ message: errorMessage, type: "error" });
      setSearchParams({}, { replace: true });
      // Close delete confirm modal on error
      setShowDeleteConfirm(null);
    }
  }, [searchParams, setSearchParams]);

  // Handle action errors
  useEffect(() => {
    if (actionData?.errors) {
      const errors = actionData.errors as any;
      const errorMessage = errors.form || errors.name || errors.status || "An error occurred";
      setToast({ message: errorMessage, type: "error" });
    }
  }, [actionData]);

  const handleEdit = (worker: any) => {
    setEditingWorker(worker);
    setShowModal(true);
  };

  const handleCloseModal = () => {
    setShowModal(false);
    setEditingWorker(null);
  };

  const handleViewShifts = (worker: any) => {
    setSelectedWorker(worker);
    setShowShiftsModal(true);
    setDateFrom('');
    setDateTo('');
    setWorkerShifts([]);
  };

  const handleCloseShiftsModal = () => {
    setShowShiftsModal(false);
    setSelectedWorker(null);
    setWorkerShifts([]);
    setDateFrom('');
    setDateTo('');
  };

  const handleFilterShifts = async () => {
    if (!selectedWorker) return;

    setIsLoadingShifts(true);
    try {
      // Build query parameters
      const params = new URLSearchParams({
        workerId: selectedWorker.id.toString()
      });
      if (dateFrom) params.append('dateFrom', dateFrom);
      if (dateTo) params.append('dateTo', dateTo);

      const response = await fetch(`/api/worker-shifts?${params.toString()}`);
      const data = await response.json();
      
      if (data.shifts) {
        setWorkerShifts(data.shifts);
      }
    } catch (error) {
      setToast({ message: "Failed to load shifts", type: "error" });
    } finally {
      setIsLoadingShifts(false);
    }
  };

  return (
    <DashboardLayout user={user}>
      {toast && (
        <Toast
          message={toast.message}
          type={toast.type}
          onClose={() => setToast(null)}
        />
      )}
      <div className="max-w-7xl mx-auto">
        <div className="mb-6 sm:mb-8">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between space-y-4 sm:space-y-0">
            <div>
              <h1 className="text-2xl sm:text-3xl font-bold text-gray-900">Workers Management</h1>
              <p className="mt-2 text-sm sm:text-base text-gray-600">Manage laborers and workers</p>
            </div>
            <button
              onClick={() => setShowModal(true)}
              className="inline-flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
              </svg>
              Add Worker
            </button>
          </div>
        </div>

        <div className="bg-white shadow-md rounded-lg overflow-hidden">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {workers.length === 0 ? (
                  <tr>
                    <td colSpan={3} className="px-6 py-12 text-center text-gray-500">
                      No workers found. Click "Add Worker" to create one.
                    </td>
                  </tr>
                ) : (
                  workers.map((worker) => (
                    <tr key={worker.id} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{worker.name}</td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${worker.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                          {worker.status}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2">
                        <button
                          onClick={() => handleViewShifts(worker)}
                          className="text-teal-600 hover:text-teal-900"
                        >
                          View Shifts
                        </button>
                        <button
                          onClick={() => handleEdit(worker)}
                          className="text-indigo-600 hover:text-indigo-900"
                        >
                          Edit
                        </button>
                        <button
                          onClick={() => setShowDeleteConfirm(worker.id)}
                          className="text-red-600 hover:text-red-900"
                        >
                          Delete
                        </button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* Add/Edit Modal */}
        {showModal && (
          <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
            <div className="relative top-20 mx-auto p-5 border w-full max-w-md shadow-lg rounded-md bg-white">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-medium text-gray-900">
                  {editingWorker ? "Edit Worker" : "Add New Worker"}
                </h3>
                <button
                  onClick={handleCloseModal}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>

              <Form method="post" className="space-y-4">
                <input type="hidden" name="intent" value={editingWorker ? "update" : "create"} />
                {editingWorker && <input type="hidden" name="id" value={editingWorker.id} />}

                <div>
                  <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-2">
                    Worker Name <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    id="name"
                    name="name"
                    required
                    defaultValue={editingWorker?.name}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                    placeholder="Enter worker name"
                  />
                </div>

                {editingWorker && (
                  <div>
                    <label htmlFor="status" className="block text-sm font-medium text-gray-700 mb-2">
                      Status <span className="text-red-500">*</span>
                    </label>
                    <select
                      id="status"
                      name="status"
                      required
                      defaultValue={editingWorker?.status}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                    >
                      <option value="active">Active</option>
                      <option value="inactive">Inactive</option>
                    </select>
                  </div>
                )}

                <div className="flex justify-end space-x-3 pt-4">
                  <button
                    type="button"
                    onClick={handleCloseModal}
                    className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
                  >
                    {isSubmitting ? "Saving..." : editingWorker ? "Update" : "Create"}
                  </button>
                </div>
              </Form>
            </div>
          </div>
        )}

        {/* View Shifts Modal */}
        {showShiftsModal && selectedWorker && (
          <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
            <div className="relative top-20 mx-auto p-5 border w-full max-w-4xl shadow-lg rounded-md bg-white">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-medium text-gray-900">
                  Shifts for {selectedWorker.name}
                </h3>
                <button
                  onClick={handleCloseShiftsModal}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>

              {/* Date Filters */}
              <div className="bg-gray-50 p-4 rounded-lg mb-4">
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                  <div>
                    <label htmlFor="dateFrom" className="block text-sm font-medium text-gray-700 mb-1">
                      From Date
                    </label>
                    <input
                      type="date"
                      id="dateFrom"
                      value={dateFrom}
                      onChange={(e) => setDateFrom(e.target.value)}
                      max={new Date().toISOString().split('T')[0]}
                      className="block w-full text-sm border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
                    />
                  </div>
                  <div>
                    <label htmlFor="dateTo" className="block text-sm font-medium text-gray-700 mb-1">
                      To Date
                    </label>
                    <input
                      type="date"
                      id="dateTo"
                      value={dateTo}
                      onChange={(e) => setDateTo(e.target.value)}
                      max={new Date().toISOString().split('T')[0]}
                      className="block w-full text-sm border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
                    />
                  </div>
                  <div className="flex items-end">
                    <button
                      onClick={handleFilterShifts}
                      disabled={isLoadingShifts}
                      className="w-full px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
                    >
                      {isLoadingShifts ? 'Loading...' : 'Filter Shifts'}
                    </button>
                  </div>
                </div>
              </div>

              {/* Shifts List */}
              <div className="max-h-96 overflow-y-auto">
                {workerShifts.length > 0 ? (
                  <div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
                    <table className="min-w-full divide-y divide-gray-200">
                      <thead className="bg-gray-50">
                        <tr>
                          <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Date
                          </th>
                          <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Shift
                          </th>
                          <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Area
                          </th>
                          <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Dredger Location
                          </th>
                          <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Employee
                          </th>
                        </tr>
                      </thead>
                      <tbody className="bg-white divide-y divide-gray-200">
                        {workerShifts.map((shift: any) => (
                          <tr key={shift.id} className="hover:bg-gray-50">
                            <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-900">
                              {new Date(shift.createdDate).toLocaleDateString('en-GB')}
                            </td>
                            <td className="px-4 py-3 whitespace-nowrap">
                              <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${shift.shift === 'day' ? 'bg-yellow-100 text-yellow-800' : 'bg-blue-100 text-blue-800'}`}>
                                {shift.shift.charAt(0).toUpperCase() + shift.shift.slice(1)}
                              </span>
                            </td>
                            <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-900">
                              {shift.area.name}
                            </td>
                            <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-900">
                              {shift.dredgerLocation.name}
                            </td>
                            <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-900">
                              {shift.employee.name}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                ) : (
                  <div className="text-center py-12 bg-gray-50 rounded-lg">
                    <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                    </svg>
                    <p className="mt-2 text-sm text-gray-500">
                      {isLoadingShifts ? 'Loading shifts...' : 'Click "Filter Shifts" to view shifts for this worker'}
                    </p>
                  </div>
                )}
              </div>

              <div className="flex justify-between items-center mt-4 pt-4 border-t border-gray-200">
                <p className="text-sm text-gray-600">
                  {workerShifts.length > 0 && `Showing ${workerShifts.length} shift${workerShifts.length !== 1 ? 's' : ''}`}
                </p>
                <button
                  onClick={handleCloseShiftsModal}
                  className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                  Close
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Delete Confirmation Modal */}
        {showDeleteConfirm && (
          <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
            <div className="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
              <div className="mt-3 text-center">
                <div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100">
                  <svg className="h-6 w-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                  </svg>
                </div>
                <h3 className="text-lg leading-6 font-medium text-gray-900 mt-4">Delete Worker</h3>
                <div className="mt-2 px-7 py-3">
                  <p className="text-sm text-gray-500">
                    Are you sure you want to delete this worker? This action cannot be undone.
                  </p>
                </div>
                <div className="flex gap-3 mt-4">
                  <button
                    onClick={() => setShowDeleteConfirm(null)}
                    className="flex-1 px-4 py-2 bg-gray-500 text-white text-base font-medium rounded-md shadow-sm hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-300"
                  >
                    Cancel
                  </button>
                  <Form method="post" className="flex-1">
                    <input type="hidden" name="intent" value="delete" />
                    <input type="hidden" name="id" value={showDeleteConfirm} />
                    <button
                      type="submit"
                      className="w-full px-4 py-2 bg-red-600 text-white text-base font-medium rounded-md shadow-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-300"
                    >
                      Delete
                    </button>
                  </Form>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </DashboardLayout>
  );
}
