'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api from '../../../../lib/api-client';
import { LayoutShell } from '../../../../components/layout-shell';
import { useState } from 'react';
import { Modal } from '../../../../components/ui/modal';

export default function PlanPeriodsPage() {
  const queryClient = useQueryClient();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [formData, setFormData] = useState({
    label: '',
    academic_year: new Date().getFullYear().toString(),
    term: 'Term 1',
    is_active: false,
  });

  const { data } = useQuery({
    queryKey: ['plan-periods'],
    queryFn: async () => {
      const response = await api.get('/plan-periods');
      return response.data;
    },
  });

  const createMutation = useMutation({
    mutationFn: async (newPeriod: typeof formData) => {
      await api.post('/plan-periods', newPeriod);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['plan-periods'] });
      setIsModalOpen(false);
      setFormData({
        label: '',
        academic_year: new Date().getFullYear().toString(),
        term: 'Term 1',
        is_active: false,
      });
    },
  });

  const statusMutation = useMutation({
    mutationFn: async ({ id, is_active }: { id: number; is_active: boolean }) => {
      await api.patch(`/plan-periods/${id}/status`, { is_active });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['plan-periods'] });
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    createMutation.mutate(formData);
  };

  return (
    <LayoutShell role="SUPER_ADMIN">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Plan periods</h1>
          <p className="text-sm text-slate-500">Manage academic years and terms.</p>
        </div>
        <button
          onClick={() => setIsModalOpen(true)}
          className="rounded-lg bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700"
        >
          New period
        </button>
      </div>

      <div className="mt-6 overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
        <table className="min-w-full divide-y divide-slate-100 text-sm">
          <thead className="bg-slate-50 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
            <tr>
              <th className="px-4 py-3">Label</th>
              <th className="px-4 py-3">Year</th>
              <th className="px-4 py-3">Term</th>
              <th className="px-4 py-3">Active</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100">
            {data?.data?.map((period: any) => (
              <tr key={period.id}>
                <td className="px-4 py-3 font-medium text-slate-900">{period.label}</td>
                <td className="px-4 py-3">{period.academic_year}</td>
                <td className="px-4 py-3">{period.term}</td>
                <td className="px-4 py-3">
                  <button
                    onClick={() => {
                        statusMutation.mutate({ id: period.id, is_active: !period.is_active });
                    }}
                    disabled={statusMutation.isPending}
                    className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-brand focus:ring-offset-2 ${
                      period.is_active ? 'bg-brand' : 'bg-slate-200'
                    } ${statusMutation.isPending ? 'opacity-50 cursor-not-allowed' : ''}`}
                    role="switch"
                    aria-checked={period.is_active}
                  >
                    <span
                      aria-hidden="true"
                      className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
                        period.is_active ? 'translate-x-5' : 'translate-x-0'
                      }`}
                    />
                  </button>
                  {period.is_active && <span className="ml-2 text-xs text-brand font-medium">Active</span>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title="New Plan Period">
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-slate-700">Label</label>
            <input
              type="text"
              required
              placeholder="e.g. 2025 Term 1"
              value={formData.label}
              onChange={(e) => setFormData({ ...formData, label: e.target.value })}
              className="mt-1 block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand focus:outline-none"
            />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700">Academic Year</label>
              <input
                type="number"
                required
                value={formData.academic_year}
                onChange={(e) => setFormData({ ...formData, academic_year: e.target.value })}
                className="mt-1 block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand focus:outline-none"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700">Term</label>
              <select
                value={formData.term}
                onChange={(e) => setFormData({ ...formData, term: e.target.value })}
                className="mt-1 block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand focus:outline-none"
              >
                <option>Term 1</option>
                <option>Term 2</option>
                <option>Term 3</option>
              </select>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              id="is_active"
              checked={formData.is_active}
              onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })}
              className="h-4 w-4 rounded border-slate-300 text-brand focus:ring-brand"
            />
            <label htmlFor="is_active" className="text-sm font-medium text-slate-700">Set as Active Period</label>
          </div>
          <div className="flex justify-end gap-3 pt-4">
            <button
              type="button"
              onClick={() => setIsModalOpen(false)}
              className="rounded-lg px-4 py-2 text-sm font-medium text-slate-600 hover:bg-slate-50"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={createMutation.isPending}
              className="rounded-lg bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700 disabled:opacity-50"
            >
              {createMutation.isPending ? 'Creating...' : 'Create Period'}
            </button>
          </div>
        </form>
      </Modal>
    </LayoutShell>
  );
}
