import { useState, useRef } from "react";
import { useParams } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Plus, Trash2, Loader2, FileText, Video, Image, Link2, Upload, Music } from "lucide-react";
import { useChapter, useChapterMaterials, useUploadMaterial, useDeleteMaterial } from "@/hooks/queries";
import { coursewareService } from "@/services/courseware.service";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast";
import type { MaterialType } from "@/types/courseware";

const typeIcons: Record<MaterialType, React.ReactNode> = {
  pdf: <FileText className="h-4 w-4" />,
  document: <FileText className="h-4 w-4" />,
  video: <Video className="h-4 w-4" />,
  audio: <Music className="h-4 w-4" />,
  image: <Image className="h-4 w-4" />,
  link: <Link2 className="h-4 w-4" />,
  article: <FileText className="h-4 w-4" />,
};

export default function ChapterDetail() {
  const { courseId, chapterId } = useParams<{ courseId: string; chapterId: string }>();
  const chId = Number(chapterId);
  const { toast } = useToast();
  const qc = useQueryClient();
  const { data: chapter, isLoading: loadingChapter } = useChapter(chId);
  const { data: materials = [], isLoading: loadingMaterials } = useChapterMaterials(chId);
  const uploadMaterial = useUploadMaterial();
  const deleteMaterial = useDeleteMaterial();
  const fileRef = useRef<HTMLInputElement>(null);

  const [showUpload, setShowUpload] = useState(false);
  const [matName, setMatName] = useState("");
  const [matType, setMatType] = useState<MaterialType>("pdf");
  const [matUrl, setMatUrl] = useState("");
  const [matFile, setMatFile] = useState<File | null>(null);
  const [allowDownload, setAllowDownload] = useState(true);

  const toggleDownload = useMutation({
    mutationFn: ({ id, allow }: { id: number; allow: boolean }) =>
      coursewareService.updateMaterial(id, { allow_download: allow }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["chapter-materials", chId] }),
    onError: () => toast({ title: "Error", description: "Failed to update material", variant: "destructive" }),
  });

  const resetForm = () => { setMatName(""); setMatType("pdf"); setMatUrl(""); setMatFile(null); setAllowDownload(true); };

  const handleUpload = () => {
    const formData = new FormData();
    formData.append("name", matName);
    formData.append("type", matType);
    formData.append("allow_download", String(allowDownload));
    if (matFile) formData.append("file", matFile);
    if (matUrl) formData.append("url", matUrl);

    uploadMaterial.mutate(
      { chapterId: chId, formData },
      {
        onSuccess: () => { toast({ title: "Material Uploaded" }); setShowUpload(false); resetForm(); },
        onError: () => toast({ title: "Error", description: "Failed to upload material", variant: "destructive" }),
      },
    );
  };

  const handleDelete = (id: number) => {
    deleteMaterial.mutate(
      { id, chapterId: chId },
      {
        onSuccess: () => toast({ title: "Material Deleted" }),
        onError: () => toast({ title: "Error", description: "Failed to delete material", variant: "destructive" }),
      },
    );
  };

  if (loadingChapter || loadingMaterials) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;

  return (
    <div className="space-y-6">
      {chapter && (
        <Card>
          <CardHeader>
            <CardTitle>{chapter.name}</CardTitle>
            <CardDescription>{chapter.description}</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex flex-wrap gap-4 text-sm">
              {chapter.start_date && <span className="text-muted-foreground">Starts: {new Date(chapter.start_date).toLocaleDateString()}</span>}
              {chapter.end_date && <span className="text-muted-foreground">Ends: {new Date(chapter.end_date).toLocaleDateString()}</span>}
              <Badge variant={chapter.is_unlocked ? "default" : "secondary"}>
                {chapter.is_unlocked ? "Unlocked" : "Locked"}
              </Badge>
              <Badge variant="outline">{chapter.unlock_mode}</Badge>
            </div>
          </CardContent>
        </Card>
      )}

      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold">Materials</h2>
        <Dialog open={showUpload} onOpenChange={setShowUpload}>
          <DialogTrigger asChild>
            <Button size="sm"><Plus className="mr-2 h-4 w-4" /> Upload Material</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>Upload Material</DialogTitle></DialogHeader>
            <div className="space-y-4 pt-4">
              <div className="space-y-2">
                <Label>Name</Label>
                <Input placeholder="Material name" value={matName} onChange={e => setMatName(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>Type</Label>
                <Select value={matType} onValueChange={v => setMatType(v as MaterialType)}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="pdf">PDF</SelectItem>
                    <SelectItem value="document">Document</SelectItem>
                    <SelectItem value="video">Video</SelectItem>
                    <SelectItem value="audio">Audio</SelectItem>
                    <SelectItem value="image">Image</SelectItem>
                    <SelectItem value="link">Link</SelectItem>
                    <SelectItem value="article">Article</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>File</Label>
                <Input ref={fileRef} type="file" onChange={e => setMatFile(e.target.files?.[0] ?? null)} />
              </div>
              <div className="space-y-2">
                <Label>Or URL</Label>
                <Input placeholder="https://..." value={matUrl} onChange={e => setMatUrl(e.target.value)} />
              </div>
              <div className="flex items-center gap-2">
                <Checkbox id="allow-dl" checked={allowDownload} onCheckedChange={v => setAllowDownload(!!v)} />
                <Label htmlFor="allow-dl">Allow Download</Label>
              </div>
              <Button className="w-full" onClick={handleUpload} disabled={uploadMaterial.isPending || !matName}>
                {uploadMaterial.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                <Upload className="mr-2 h-4 w-4" /> Upload
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-12">#</TableHead>
              <TableHead>Name</TableHead>
              <TableHead>Type</TableHead>
              <TableHead>Download</TableHead>
              <TableHead className="w-16">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {materials
              .sort((a, b) => a.sequence - b.sequence)
              .map(m => (
                <TableRow key={m.id}>
                  <TableCell className="text-muted-foreground">{m.sequence}</TableCell>
                  <TableCell className="flex items-center gap-2">
                    {typeIcons[m.type]}
                    <span>{m.name}</span>
                  </TableCell>
                  <TableCell><Badge variant="outline">{m.type}</Badge></TableCell>
                  <TableCell>
                    <Checkbox
                      checked={m.allow_download}
                      onCheckedChange={v => toggleDownload.mutate({ id: m.id, allow: !!v })}
                    />
                  </TableCell>
                  <TableCell>
                    <Button variant="ghost" size="icon" onClick={() => handleDelete(m.id)} disabled={deleteMaterial.isPending}>
                      <Trash2 className="h-4 w-4 text-destructive" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            {materials.length === 0 && (
              <TableRow>
                <TableCell colSpan={5} className="text-center text-muted-foreground py-8">No materials uploaded yet.</TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </Card>
    </div>
  );
}
