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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Plus, Trash2, Loader2, FileText, Video, Image, Link2, Upload, Music, Library, Search, CheckCircle2 } from "lucide-react";
import { useChapter, useChapterMaterials, useUploadMaterial, useDeleteMaterial, useCreateMaterialFromResource } from "@/hooks/queries";
import { coursewareService } from "@/services/courseware.service";
import { resourcesService } from "@/services/resources.service";
import { useMutation, useQuery, 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 fromResource = useCreateMaterialFromResource();
  const fileRef = useRef<HTMLInputElement>(null);

  const [showUpload, setShowUpload] = useState(false);
  const [dialogTab, setDialogTab] = useState<string>("library");
  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 [libSearch, setLibSearch] = useState("");
  const [libTypeFilter, setLibTypeFilter] = useState("all");
  const [selectedResourceId, setSelectedResourceId] = useState<number | null>(null);

  const { data: resourcesData, isLoading: loadingResources } = useQuery({
    queryKey: ["resources", "list", { search: libSearch, resource_type: libTypeFilter === "all" ? undefined : libTypeFilter }],
    queryFn: () => resourcesService.list({
      search: libSearch || undefined,
      resource_type: libTypeFilter === "all" ? undefined : libTypeFilter,
      size: 50,
    }),
    enabled: showUpload,
  });
  const libraryResources = resourcesData?.items ?? [];

  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); setSelectedResourceId(null); setLibSearch("");
    setLibTypeFilter("all"); setDialogTab("library");
  };

  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 handleAddFromLibrary = () => {
    if (!selectedResourceId) return;
    fromResource.mutate(
      { chapterId: chId, resourceId: selectedResourceId },
      {
        onSuccess: () => { toast({ title: "Material added from library" }); setShowUpload(false); resetForm(); },
        onError: () => toast({ title: "Error", description: "Failed to add material from library", 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={(open) => { setShowUpload(open); if (!open) resetForm(); }}>
          <DialogTrigger asChild>
            <Button size="sm"><Plus className="mr-2 h-4 w-4" /> Add Material</Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[600px]">
            <DialogHeader><DialogTitle>Add Material</DialogTitle></DialogHeader>
            <Tabs value={dialogTab} onValueChange={setDialogTab} className="pt-2">
              <TabsList className="w-full">
                <TabsTrigger value="library" className="flex-1">
                  <Library className="mr-2 h-4 w-4" /> From Library
                </TabsTrigger>
                <TabsTrigger value="upload" className="flex-1">
                  <Upload className="mr-2 h-4 w-4" /> Upload Manual
                </TabsTrigger>
              </TabsList>

              {/* Tab: From Library */}
              <TabsContent value="library" className="space-y-4 pt-2">
                <div className="flex gap-2">
                  <div className="relative flex-1">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input
                      placeholder="Search resources…"
                      value={libSearch}
                      onChange={e => setLibSearch(e.target.value)}
                      className="pl-9"
                    />
                  </div>
                  <Select value={libTypeFilter} onValueChange={setLibTypeFilter}>
                    <SelectTrigger className="w-[120px]"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Types</SelectItem>
                      <SelectItem value="pdf">PDF</SelectItem>
                      <SelectItem value="video">Video</SelectItem>
                      <SelectItem value="document">Document</SelectItem>
                      <SelectItem value="link">Link</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="max-h-[300px] overflow-y-auto border rounded-md">
                  {loadingResources ? (
                    <div className="flex justify-center py-8">
                      <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
                    </div>
                  ) : libraryResources.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground text-sm">
                      No resources found. Try a different search or upload manually.
                    </div>
                  ) : (
                    <div className="divide-y">
                      {libraryResources.map(r => {
                        const selected = selectedResourceId === r.id;
                        return (
                          <button
                            key={r.id}
                            type="button"
                            onClick={() => setSelectedResourceId(selected ? null : r.id)}
                            className={`w-full text-left px-4 py-3 flex items-center gap-3 transition-colors hover:bg-muted/50 ${
                              selected ? "bg-primary/10 ring-1 ring-primary/30" : ""
                            }`}
                          >
                            <div className="shrink-0">
                              {selected ? (
                                <CheckCircle2 className="h-5 w-5 text-primary" />
                              ) : (
                                typeIcons[r.resource_type as MaterialType] ?? <FileText className="h-5 w-5 text-muted-foreground" />
                              )}
                            </div>
                            <div className="flex-1 min-w-0">
                              <p className="font-medium text-sm truncate">{r.name}</p>
                              <p className="text-xs text-muted-foreground">
                                {r.resource_type} {r.topic_names?.length ? `· ${r.topic_names.slice(0, 2).join(", ")}` : ""}
                              </p>
                            </div>
                            <Badge variant="outline" className="capitalize shrink-0">{r.resource_type}</Badge>
                          </button>
                        );
                      })}
                    </div>
                  )}
                </div>

                <Button
                  className="w-full"
                  onClick={handleAddFromLibrary}
                  disabled={!selectedResourceId || fromResource.isPending}
                >
                  {fromResource.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  <Library className="mr-2 h-4 w-4" />
                  Add Selected Resource
                </Button>
              </TabsContent>

              {/* Tab: Manual Upload */}
              <TabsContent value="upload" className="space-y-4 pt-2">
                <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>
              </TabsContent>
            </Tabs>
          </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 added yet.</TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </Card>
    </div>
  );
}
