"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import Image from "next/image";
import { PageHeader } from "@/components/admin/PageHeader";
import { DataTable, type Column } from "@/components/admin/DataTable";
import { FormSheet } from "@/components/admin/FormSheet";
import { ImageDropZone } from "@/components/admin/ImageDropZone";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { Plus, Trash2, Video, Upload, X, Search, CheckCircle2 } from "lucide-react";
import { toast } from "sonner";
import { useImageUpload } from "@/hooks/use-image-upload";
import { uploadToCloudinary } from "@/lib/cloudinary";
import {
  getTechnologies,
  createTechnology,
  updateTechnology,
  deleteTechnology,
  type Technology,
} from "@/services/technologies";
import { useAdminLocale } from "@/hooks/use-admin-locale";

interface FormSpec {
  label: string;
  value: string;
}

interface FormState {
  name: string;
  subtitle: string;
  overview: string;
  howItWorks: string;
  specs: FormSpec[];
  applications: string[];
}

const emptyForm = (): FormState => ({
  name: "",
  subtitle: "",
  overview: "",
  howItWorks: "",
  specs: [{ label: "", value: "" }],
  applications: [""],
});

export default function TechnologiesAdmin() {
  const locale = useAdminLocale();
  const [techs, setTechs] = useState<Technology[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [editing, setEditing] = useState<Technology | null>(null);
  const [isAdding, setIsAdding] = useState(false);
  const [form, setForm] = useState<FormState>(emptyForm());
  const [isSaving, setIsSaving] = useState(false);
  const [deletingId, setDeletingId] = useState<number | null>(null);

  const { preview, file: imageFile, isDragging, setIsDragging, inputRef, handleFile, onDrop, reset: resetUpload } = useImageUpload();

  const [videoPreview, setVideoPreview] = useState<string | null>(null);
  const [videoFile, setVideoFile] = useState<File | null>(null);
  const [videoDragging, setVideoDragging] = useState(false);
  const videoInputRef = useRef<HTMLInputElement>(null);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const [imageProgress, setImageProgress] = useState<number | null>(null);
  const [imageUploadDone, setImageUploadDone] = useState(false);
  const [videoProgress, setVideoProgress] = useState<number | null>(null);
  const [videoUploadDone, setVideoUploadDone] = useState(false);
  const [videoRemoved, setVideoRemoved] = useState(false);

  const fetchTechs = (query?: string) => {
    setLoading(true);
    getTechnologies(query)
      .then(setTechs)
      .finally(() => setLoading(false));
  };

  useEffect(() => { fetchTechs(); }, []);

  const handleSearchChange = (value: string) => {
    setSearch(value);
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => fetchTechs(value), 400);
  };

  const handleVideoFile = useCallback((f: File) => {
    if (!f.type.startsWith("video/")) { toast.error("Only video files are allowed (MP4, MOV, WEBM)."); return; }
    if (f.size > 30 * 1024 * 1024) { toast.error("Video must be smaller than 30 MB."); return; }
    setVideoFile(f);
    setVideoPreview((prev) => { if (prev) URL.revokeObjectURL(prev); return URL.createObjectURL(f); });
  }, []);

  const onVideoDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setVideoDragging(false);
    const dropped = e.dataTransfer.files[0];
    if (dropped) handleVideoFile(dropped);
  }, [handleVideoFile]);

  const resetVideoUpload = useCallback(() => {
    setVideoPreview((prev) => { if (prev) URL.revokeObjectURL(prev); return null; });
    setVideoFile(null);
  }, []);

  const resetSheet = () => {
    setEditing(null);
    setIsAdding(false);
    setForm(emptyForm());
    resetUpload();
    resetVideoUpload();
    setImageProgress(null);
    setImageUploadDone(false);
    setVideoProgress(null);
    setVideoUploadDone(false);
    setVideoRemoved(false);
  };

  const openEdit = (t: Technology) => {
    resetUpload();
    resetVideoUpload();
    setVideoRemoved(false);
    setImageUploadDone(false);
    setVideoUploadDone(false);
    setForm({
      name: t.name,
      subtitle: t.subtitle ?? "",
      overview: t.overview ?? "",
      howItWorks: t.how_it_works ?? "",
      specs: t.specs.length ? t.specs.map((s) => ({ label: s.label, value: s.value })) : [{ label: "", value: "" }],
      applications: t.applications.length ? t.applications.map((a) => a.application) : [""],
    });
    setEditing(t);
  };

  const set = <K extends keyof FormState>(key: K, value: FormState[K]) =>
    setForm((prev) => ({ ...prev, [key]: value }));

  const updateSpec = (i: number, field: keyof FormSpec, value: string) =>
    setForm((prev) => ({ ...prev, specs: prev.specs.map((s, idx) => idx === i ? { ...s, [field]: value } : s) }));

  const addSpec = () => setForm((prev) => ({ ...prev, specs: [...prev.specs, { label: "", value: "" }] }));
  const removeSpec = (i: number) => setForm((prev) => ({ ...prev, specs: prev.specs.filter((_, idx) => idx !== i) }));

  const updateApplication = (i: number, value: string) =>
    setForm((prev) => ({ ...prev, applications: prev.applications.map((a, idx) => idx === i ? value : a) }));

  const addApplication = () => setForm((prev) => ({ ...prev, applications: [...prev.applications, ""] }));
  const removeApplication = (i: number) => setForm((prev) => ({ ...prev, applications: prev.applications.filter((_, idx) => idx !== i) }));

  const handleSave = async () => {
    if (!form.name.trim()) { toast.error("Name is required."); return; }
    setIsSaving(true);

    let imageResult: { secure_url: string; public_id: string } | undefined;
    let videoResult: { secure_url: string; public_id: string } | undefined;

    try {
      if (imageFile) {
        setImageProgress(0);
        imageResult = await uploadToCloudinary(imageFile, "image", setImageProgress);
        setImageProgress(null);
        setImageUploadDone(true);
      }
      if (videoFile) {
        setVideoProgress(0);
        videoResult = await uploadToCloudinary(videoFile, "video", setVideoProgress);
        setVideoProgress(null);
        setVideoUploadDone(true);
      }
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Media upload failed.");
      setImageProgress(null);
      setVideoProgress(null);
      setIsSaving(false);
      return;
    }

    const specs = form.specs.filter((s) => s.label.trim());
    const applications = form.applications.filter((a) => a.trim());
    try {
      if (isAdding) {
        const created = await createTechnology({
          name: form.name,
          subtitle: form.subtitle,
          overview: form.overview,
          how_it_works: form.howItWorks,
          image_path: imageResult?.secure_url,
          image_public_id: imageResult?.public_id,
          video_path: videoResult?.secure_url,
          video_public_id: videoResult?.public_id,
          specs,
          applications,
        });
        setTechs((prev) => [...prev, created]);
        toast.success("Technology added.");
      } else {
        const updated = await updateTechnology(editing!.id, {
          name: { [locale]: form.name },
          subtitle: { [locale]: form.subtitle },
          overview: { [locale]: form.overview },
          how_it_works: { [locale]: form.howItWorks },
          image_path: imageResult?.secure_url,
          image_public_id: imageResult?.public_id,
          video_path: videoResult ? videoResult.secure_url : videoRemoved ? null : undefined,
          video_public_id: videoResult ? videoResult.public_id : videoRemoved ? null : undefined,
          specs: specs.map((s) => ({ label: { [locale]: s.label }, value: { [locale]: s.value } })),
          applications: applications.map((a) => ({ [locale]: a })),
        });
        setTechs((prev) => prev.map((t) => t.id === updated.id ? updated : t));
        toast.success("Technology updated.");
      }
      resetSheet();
    } catch {
      // interceptor shows error toast
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async (t: Technology) => {
    if (deletingId) return;
    setDeletingId(t.id);
    try {
      await deleteTechnology(t.id, t.image_public_id, t.video_public_id);
      setTechs((prev) => prev.filter((x) => x.id !== t.id));
      toast.success("Technology removed.");
    } catch {
      // interceptor shows error toast
    } finally {
      setDeletingId(null);
    }
  };

  const columns: Column<Technology>[] = [
    {
      key: "name",
      label: "Technology",
      render: (t) => (
        <div className="flex items-center gap-3">
          {t.image_path ? (
            <Image src={t.image_path} alt={t.name} width={56} height={40} className="h-10 w-14 object-cover rounded" />
          ) : (
            <div className="h-10 w-14 rounded bg-muted" />
          )}
          <div>
            <div className="font-medium text-sm">{t.name}</div>
            <div className="text-xs text-muted-foreground">{t.subtitle}</div>
          </div>
        </div>
      ),
    },
    {
      key: "specs",
      label: "Specs",
      render: (t) => <Badge variant="secondary">{t.specs.length} specs</Badge>,
      className: "w-24",
    },
    {
      key: "applications",
      label: "Applications",
      render: (t) => <Badge variant="outline">{t.applications.length} items</Badge>,
      className: "w-28",
    },
    {
      key: "video_path",
      label: "Video",
      render: (t) =>
        t.video_path ? (
          <Badge variant="secondary" className="gap-1 text-[10px]">
            <Video className="h-3 w-3" /> Yes
          </Badge>
        ) : (
          <Badge variant="outline" className="text-[10px]">None</Badge>
        ),
      className: "w-20",
    },
  ];

  const sheetOpen = isAdding || !!editing;

  return (
    <div className="p-6 lg:p-8 max-w-7xl mx-auto">
      <PageHeader
        title="Technologies"
        description="Manage inspection and NDT technology listings."
        onAdd={() => { setForm(emptyForm()); setIsAdding(true); }}
        addLabel="Add Technology"
      />

      <div className="relative max-w-sm mb-4">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input
          placeholder="Search technologies…"
          value={search}
          onChange={(e) => handleSearchChange(e.target.value)}
          className="pl-9 h-9"
        />
      </div>

      {loading ? (
        <div className="space-y-2">
          {Array.from({ length: 5 }).map((_, i) => <Skeleton key={i} className="h-14 w-full rounded-md" />)}
        </div>
      ) : (
        <DataTable
          data={techs}
          columns={columns}
          onEdit={openEdit}
          onDelete={handleDelete}
        />
      )}

      <FormSheet
        open={sheetOpen}
        onOpenChange={(open) => !open && resetSheet()}
        title={isAdding ? "Add Technology" : `Edit: ${editing?.name}`}
        onSave={handleSave}
        loading={isSaving}
      >
        {/* Basic Info */}
        <div className="space-y-2">
          <Label>Name</Label>
          <Input value={form.name} onChange={(e) => set("name", e.target.value)} placeholder="e.g. SLOFEC® FloorScanner" />
        </div>
        <div className="space-y-2">
          <Label>Subtitle</Label>
          <Input value={form.subtitle} onChange={(e) => set("subtitle", e.target.value)} placeholder="e.g. Tank Floor Inspection" />
        </div>

        {/* Image */}
        <div className="space-y-2">
          <Label>Image</Label>
          <input ref={inputRef} type="file" accept="image/*" className="hidden" onChange={(e) => e.target.files?.[0] && handleFile(e.target.files[0])} />
          <ImageDropZone
            preview={preview}
            fallback={editing?.image_path ?? undefined}
            isDragging={isDragging}
            onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
            onDragLeave={() => setIsDragging(false)}
            onDrop={onDrop}
            onClick={() => inputRef.current?.click()}
          />
          {imageProgress !== null && (
            <div className="space-y-1">
              <div className="flex justify-between text-xs text-muted-foreground">
                <span>Uploading image…</span>
                <span>{imageProgress}%</span>
              </div>
              <div className="h-1.5 w-full rounded-full bg-muted overflow-hidden">
                <div className="h-full bg-primary rounded-full transition-all duration-150" style={{ width: `${imageProgress}%` }} />
              </div>
            </div>
          )}
          {imageUploadDone && imageProgress === null && (
            <div className="flex items-center gap-1.5 text-xs text-emerald-600">
              <CheckCircle2 className="h-3.5 w-3.5" />
              <span>Image uploaded</span>
            </div>
          )}
        </div>

        {/* Video */}
        <div className="space-y-2">
          <Label>Video <span className="text-xs text-muted-foreground">(optional)</span></Label>
          <input
            ref={videoInputRef}
            type="file"
            accept="video/*"
            className="hidden"
            onChange={(e) => e.target.files?.[0] && handleVideoFile(e.target.files[0])}
          />
          <div
            className={`border-2 border-dashed rounded-lg p-5 text-center text-sm cursor-pointer transition-colors ${
              videoDragging ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-muted/50"
            } text-muted-foreground`}
            onClick={() => videoInputRef.current?.click()}
            onDragOver={(e) => { e.preventDefault(); setVideoDragging(true); }}
            onDragLeave={() => setVideoDragging(false)}
            onDrop={onVideoDrop}
          >
            {videoFile || (editing?.video_path && !videoRemoved) ? (
              <div className="flex flex-col items-center gap-2">
                <Video className="h-8 w-8 text-primary/60" />
                <span className="text-xs font-medium text-foreground truncate max-w-full">
                  {videoFile?.name ?? "Current video"}
                </span>
                <button
                  type="button"
                  className="text-xs text-destructive hover:underline flex items-center gap-1"
                  onClick={(e) => { e.stopPropagation(); resetVideoUpload(); setVideoRemoved(true); }}
                >
                  <X className="h-3 w-3" /> Remove video
                </button>
              </div>
            ) : (
              <div className="flex flex-col items-center gap-2">
                <Upload className="h-8 w-8 text-muted-foreground/50" />
                <span>Click to upload or drag &amp; drop</span>
                <span className="text-xs text-muted-foreground/60">MP4, MOV, WEBM</span>
              </div>
            )}
          </div>
          {videoProgress !== null && (
            <div className="space-y-1">
              <div className="flex justify-between text-xs text-muted-foreground">
                <span>Uploading video…</span>
                <span>{videoProgress}%</span>
              </div>
              <div className="h-1.5 w-full rounded-full bg-muted overflow-hidden">
                <div className="h-full bg-primary rounded-full transition-all duration-150" style={{ width: `${videoProgress}%` }} />
              </div>
            </div>
          )}
          {videoUploadDone && videoProgress === null && (
            <div className="flex items-center gap-1.5 text-xs text-emerald-600">
              <CheckCircle2 className="h-3.5 w-3.5" />
              <span>Video uploaded</span>
            </div>
          )}
        </div>

        <Separator />

        {/* Overview */}
        <div className="space-y-2">
          <Label>Overview</Label>
          <Textarea value={form.overview} onChange={(e) => set("overview", e.target.value)} rows={4} placeholder="Brief description of the technology…" />
        </div>

        {/* How It Works */}
        <div className="space-y-2">
          <Label>How It Works</Label>
          <Textarea value={form.howItWorks} onChange={(e) => set("howItWorks", e.target.value)} rows={4} placeholder="Explain the working principle…" />
        </div>

        <Separator />

        {/* Specs */}
        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <Label>Technical Specifications</Label>
            <Button type="button" variant="outline" size="sm" onClick={addSpec} className="h-7 text-xs gap-1">
              <Plus className="h-3 w-3" /> Add Spec
            </Button>
          </div>
          {form.specs.map((spec, i) => (
            <div key={i} className="flex gap-2 items-start">
              <Input value={spec.label} onChange={(e) => updateSpec(i, "label", e.target.value)} placeholder="Label" className="text-sm" />
              <Input value={spec.value} onChange={(e) => updateSpec(i, "value", e.target.value)} placeholder="Value" className="text-sm" />
              <Button type="button" variant="ghost" size="icon" className="h-9 w-9 shrink-0 text-muted-foreground hover:text-destructive" onClick={() => removeSpec(i)}>
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>
          ))}
        </div>

        <Separator />

        {/* Applications */}
        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <Label>Key Applications</Label>
            <Button type="button" variant="outline" size="sm" onClick={addApplication} className="h-7 text-xs gap-1">
              <Plus className="h-3 w-3" /> Add
            </Button>
          </div>
          {form.applications.map((app, i) => (
            <div key={i} className="flex gap-2 items-center">
              <Input value={app} onChange={(e) => updateApplication(i, e.target.value)} placeholder="e.g. Tank floor corrosion mapping" className="text-sm" />
              <Button type="button" variant="ghost" size="icon" className="h-9 w-9 shrink-0 text-muted-foreground hover:text-destructive" onClick={() => removeApplication(i)}>
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>
          ))}
        </div>
      </FormSheet>
    </div>
  );
}
