'use client';

import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetFooter,
} from '@/components/ui/sheet';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { toast } from 'sonner';
import { Trash2, Edit, Upload, Plus } from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';

type AllowedStudent = {
  id: string;
  email: string;
  levels: string;
  active: boolean;
  createdAt: string;
  updatedAt: string;
};

export default function AllowedStudentsClient() {
  const [students, setStudents] = useState<AllowedStudent[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isDeleteAlertOpen, setIsDeleteAlertOpen] = useState(false);
  const [isImportLoading, setIsImportLoading] = useState(false);
  const [editingStudent, setEditingStudent] = useState<AllowedStudent | null>(null);
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [newEmail, setNewEmail] = useState('');
  const [newLevels, setNewLevels] = useState('');

  // Fetch students on mount
  useEffect(() => {
    fetchStudents();
  }, []);

  const fetchStudents = async () => {
    setIsLoading(true);
    try {
      const res = await fetch('/api/admin/allowed-students');
      if (res.ok) {
        const data = await res.json();
        setStudents(data);
      } else {
        toast.error('Failed to fetch students');
      }
    } catch (err) {
      console.error('Failed to fetch students:', err);
      toast.error('Error fetching students');
    } finally {
      setIsLoading(false);
    }
  };

  const handleAddStudent = async () => {
    if (!newEmail.trim() || !newLevels.trim()) {
      toast.error('Email and course codes required');
      return;
    }

    try {
      const res = await fetch('/api/admin/allowed-students', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: newEmail.trim(),
          levels: newLevels.trim(),
        }),
      });

      if (res.status === 201) {
        toast.success('Student added');
        setNewEmail('');
        setNewLevels('');
        setIsAddDialogOpen(false);
        fetchStudents();
      } else if (res.status === 409) {
        toast.error('Email already registered');
      } else {
        const data = await res.json();
        toast.error(data.error || 'Failed to add student');
      }
    } catch (err) {
      console.error('Failed to add student:', err);
      toast.error('Error adding student');
    }
  };

  const handleEditStudent = async () => {
    if (!editingStudent) return;

    try {
      const res = await fetch('/api/admin/allowed-students', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          id: editingStudent.id,
          email: editingStudent.email,
          levels: editingStudent.levels,
          active: editingStudent.active,
        }),
      });

      if (res.ok) {
        toast.success('Student updated');
        setIsEditDialogOpen(false);
        setEditingStudent(null);
        fetchStudents();
      } else {
        const data = await res.json();
        toast.error(data.error || 'Failed to update student');
      }
    } catch (err) {
      console.error('Failed to update student:', err);
      toast.error('Error updating student');
    }
  };

  const handleDeleteStudent = async () => {
    if (!deleteId) return;

    try {
      const res = await fetch(`/api/admin/allowed-students?id=${deleteId}`, {
        method: 'DELETE',
      });

      if (res.ok) {
        toast.success('Student removed');
        setIsDeleteAlertOpen(false);
        setDeleteId(null);
        fetchStudents();
      } else {
        toast.error('Failed to delete student');
      }
    } catch (err) {
      console.error('Failed to delete student:', err);
      toast.error('Error deleting student');
    }
  };

  const handleImportCSV = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setIsImportLoading(true);
    try {
      const formData = new FormData();
      formData.append('file', file);

      const res = await fetch('/api/admin/allowed-students/import', {
        method: 'POST',
        body: formData,
      });

      if (res.ok) {
        const result = await res.json();
        toast.success(`Imported: ${result.imported}, Updated: ${result.updated}`);
        if (result.errors.length > 0) {
          toast.warning(`${result.errors.length} errors during import`);
        }
        fetchStudents();
      } else {
        const data = await res.json();
        toast.error(data.error || 'Failed to import students');
      }
    } catch (err) {
      console.error('Failed to import CSV:', err);
      toast.error('Error importing students');
    } finally {
      setIsImportLoading(false);
    }
  };

  if (isLoading) {
    return <div className="p-4 text-sm text-muted-foreground">Loading allowed students...</div>;
  }

  return (
    <div className="flex flex-col gap-6 py-4 md:gap-6 md:py-6 px-4 lg:px-16">
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>Allowed Students ({students.length})</CardTitle>
          <div className="flex gap-2">
            <Button
              size="sm"
              onClick={() => setIsAddDialogOpen(true)}
              className="gap-2"
            >
              <Plus className="h-4 w-4" />
              Add Student
            </Button>
            <div className="relative">
              <input
                type="file"
                accept=".csv"
                onChange={handleImportCSV}
                disabled={isImportLoading}
                className="hidden"
                id="csv-upload"
              />
              <Button
                size="sm"
                variant="outline"
                onClick={() => document.getElementById('csv-upload')?.click()}
                disabled={isImportLoading}
                className="gap-2"
              >
                <Upload className="h-4 w-4" />
                Import CSV
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Email</TableHead>
                <TableHead>Course Codes</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Added</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {students.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} className="text-center text-muted-foreground">
                    No students added yet
                  </TableCell>
                </TableRow>
              ) : (
                students.map((student) => (
                  <TableRow key={student.id}>
                    <TableCell className="font-medium">{student.email}</TableCell>
                    <TableCell>
                      <div className="flex flex-wrap gap-1">
                        {student.levels.split(',').map((code) => (
                          <Badge key={code.trim()} variant="outline">
                            {code.trim()}
                          </Badge>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant={student.active ? 'default' : 'secondary'}>
                        {student.active ? 'Active' : 'Inactive'}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-sm text-muted-foreground">
                      {formatDistanceToNow(new Date(student.createdAt), { addSuffix: true })}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => {
                            setEditingStudent(student);
                            setIsEditDialogOpen(true);
                          }}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          size="sm"
                          variant="destructive"
                          onClick={() => {
                            setDeleteId(student.id);
                            setIsDeleteAlertOpen(true);
                          }}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Add Student Sheet */}
      <Sheet open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
        <SheetContent>
          <SheetHeader>
            <SheetTitle>Add Student</SheetTitle>
          </SheetHeader>
          <div className="flex flex-col gap-4 mt-4">
            <div>
              <label className="text-sm font-medium">Email</label>
              <Input
                placeholder="student@university.edu"
                value={newEmail}
                onChange={(e) => setNewEmail(e.target.value)}
              />
            </div>
            <div>
              <label className="text-sm font-medium">Course Codes</label>
              <Input
                placeholder="3D100,3D200,3D300"
                value={newLevels}
                onChange={(e) => setNewLevels(e.target.value)}
              />
              <p className="text-xs text-muted-foreground mt-1">
                Comma-separated course codes
              </p>
            </div>
          </div>
          <SheetFooter className="mt-6">
            <Button variant="outline" onClick={() => setIsAddDialogOpen(false)}>
              Cancel
            </Button>
            <Button onClick={handleAddStudent}>Add Student</Button>
          </SheetFooter>
        </SheetContent>
      </Sheet>

      {/* Edit Student Sheet */}
      <Sheet open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <SheetContent>
          <SheetHeader>
            <SheetTitle>Edit Student</SheetTitle>
          </SheetHeader>
          {editingStudent && (
            <div className="flex flex-col gap-4 mt-4">
              <div>
                <label className="text-sm font-medium">Email</label>
                <Input
                  value={editingStudent.email}
                  onChange={(e) =>
                    setEditingStudent({ ...editingStudent, email: e.target.value })
                  }
                />
              </div>
              <div>
                <label className="text-sm font-medium">Course Codes</label>
                <Input
                  placeholder="3D100,3D200,3D300"
                  value={editingStudent.levels}
                  onChange={(e) =>
                    setEditingStudent({ ...editingStudent, levels: e.target.value })
                  }
                />
              </div>
            </div>
          )}
          <SheetFooter className="mt-6">
            <Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>
              Cancel
            </Button>
            <Button onClick={handleEditStudent}>Save Changes</Button>
          </SheetFooter>
        </SheetContent>
      </Sheet>

      {/* Delete Confirmation */}
      <AlertDialog open={isDeleteAlertOpen} onOpenChange={setIsDeleteAlertOpen}>
        <AlertDialogContent>
          <AlertDialogTitle>Remove Student</AlertDialogTitle>
          <AlertDialogDescription>
            Are you sure? The student will be prevented from logging in, but their existing enrollments will remain.
          </AlertDialogDescription>
          <div className="flex justify-end gap-2">
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={handleDeleteStudent} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
              Remove
            </AlertDialogAction>
          </div>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
