"use client";

import { useEffect, useState } from "react";
import { useRouter, useParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Loader2, ArrowLeft, X, FileText } from "lucide-react";
import { toast } from "sonner";
import api from "@/lib/api";
import Link from "next/link";
import { PageHeaderSkeleton } from "@/components/shared";
import type { MagazineIssue } from "@/lib/types";

export default function EditIssuePage() {
  const router = useRouter();
  const params = useParams();
  const issueId = params.id as string;
  const [loading, setLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [form, setForm] = useState({
    title: "",
    description: "",
    volume_number: "",
    issue_number: "",
    status: "draft",
    published_at: "",
  });
  const [cover, setCover] = useState<File | null>(null);
  const [existingCover, setExistingCover] = useState<string | null>(null);
  const [pdfFile, setPdfFile] = useState<File | null>(null);
  const [existingPdf, setExistingPdf] = useState<{ name: string; size: number } | null>(null);

  useEffect(() => {
    api.get(`/api/magazine/issues/${issueId}/edit`).then(({ data }) => {
      const issue: MagazineIssue = data.data;
      setForm({
        title: issue.title,
        description: issue.description || "",
        volume_number: String(issue.volume_number || ""),
        issue_number: String(issue.issue_number || ""),
        status: issue.status,
        published_at: issue.published_at ? issue.published_at.split("T")[0] : "",
      });
      setExistingCover(issue.cover_image || issue.cover_thumbnail || null);
      if (issue.has_pdf && issue.pdf_file_name) {
        setExistingPdf({ name: issue.pdf_file_name, size: issue.pdf_file_size || 0 });
      }
      setLoading(false);
    }).catch(() => {
      toast.error("Failed to load issue");
      router.push("/dashboard/magazine/issues");
    });
  }, [issueId]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    try {
      const formData = new FormData();
      Object.entries(form).forEach(([key, value]) => {
        if (value) formData.append(key, value);
      });
      if (cover) formData.append("cover_image", cover);
      if (pdfFile) formData.append("pdf_file", pdfFile);

      await api.post(`/api/magazine/issues/${issueId}/update`, formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });
      toast.success("Issue updated");
      router.push("/dashboard/magazine/issues");
    } catch (err: any) {
      toast.error(err.response?.data?.message || "Failed to update issue");
    } finally {
      setIsSubmitting(false);
    }
  };

  if (loading) return <PageHeaderSkeleton />;

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="sm" asChild>
          <Link href="/dashboard/magazine/issues">
            <ArrowLeft className="mr-2 h-4 w-4" /> Back
          </Link>
        </Button>
        <div>
          <h1 className="font-display text-2xl font-semibold">Edit Issue</h1>
          <p className="text-sm text-muted-foreground">Update magazine issue</p>
        </div>
      </div>

      <form onSubmit={handleSubmit}>
        <div className="grid gap-6 lg:grid-cols-3">
          <Card className="lg:col-span-2">
            <CardHeader>
              <CardTitle className="text-base">Issue Details</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label>Title *</Label>
                <Input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} required />
              </div>
              <div className="space-y-2">
                <Label>Description</Label>
                <Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} rows={4} />
              </div>
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label>Volume Number</Label>
                  <Input type="number" value={form.volume_number} onChange={(e) => setForm({ ...form, volume_number: e.target.value })} min={1} />
                </div>
                <div className="space-y-2">
                  <Label>Issue Number</Label>
                  <Input type="number" value={form.issue_number} onChange={(e) => setForm({ ...form, issue_number: e.target.value })} min={1} />
                </div>
              </div>
            </CardContent>
          </Card>

          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Publishing</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label>Status</Label>
                  <Select value={form.status} onValueChange={(v) => setForm({ ...form, status: v })}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="draft">Draft</SelectItem>
                      <SelectItem value="published">Published</SelectItem>
                      <SelectItem value="archived">Archived</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>Publish Date</Label>
                  <Input type="date" value={form.published_at} onChange={(e) => setForm({ ...form, published_at: e.target.value })} />
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">Cover Image</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                {/* Existing cover preview */}
                {existingCover && !cover && (
                  <div className="relative">
                    <div className="relative aspect-[3/4] w-32 overflow-hidden rounded-md border">
                      <img src={existingCover} alt="Current cover" className="h-full w-full object-cover" />
                    </div>
                    <p className="mt-1 text-xs text-muted-foreground">Current cover image</p>
                  </div>
                )}
                {/* New cover preview */}
                {cover && (
                  <div className="relative">
                    <div className="relative aspect-[3/4] w-32 overflow-hidden rounded-md border">
                      <img src={URL.createObjectURL(cover)} alt="New cover preview" className="h-full w-full object-cover" />
                    </div>
                    <Button
                      type="button"
                      variant="destructive"
                      size="sm"
                      className="mt-2"
                      onClick={() => setCover(null)}
                    >
                      <X className="mr-1 h-3 w-3" /> Remove
                    </Button>
                  </div>
                )}
                <div className="space-y-1">
                  <Label>{existingCover ? "Replace cover" : "Upload cover"}</Label>
                  <Input type="file" accept="image/*" onChange={(e) => setCover(e.target.files?.[0] || null)} />
                  <p className="text-xs text-muted-foreground">Recommended 600×800. Max 4MB.</p>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">PDF File</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                {/* Existing PDF info */}
                {existingPdf && !pdfFile && (
                  <div className="flex items-center gap-2 rounded-md border border-green-200 bg-green-50 p-3 dark:border-green-800 dark:bg-green-950">
                    <FileText className="h-5 w-5 text-green-600" />
                    <div className="min-w-0 flex-1">
                      <p className="truncate text-sm font-medium">{existingPdf.name}</p>
                      <p className="text-xs text-muted-foreground">
                        {existingPdf.size ? `${(existingPdf.size / 1024 / 1024).toFixed(2)} MB` : "Uploaded"}
                      </p>
                    </div>
                  </div>
                )}
                {/* New PDF preview */}
                {pdfFile && (
                  <div className="flex items-center gap-2 rounded-md border p-3">
                    <FileText className="h-5 w-5 text-red-500" />
                    <div className="min-w-0 flex-1">
                      <p className="truncate text-sm font-medium">{pdfFile.name}</p>
                      <p className="text-xs text-muted-foreground">{(pdfFile.size / 1024 / 1024).toFixed(2)} MB</p>
                    </div>
                    <Button type="button" variant="ghost" size="sm" onClick={() => setPdfFile(null)}>
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                )}
                <div className="space-y-1">
                  <Label>{existingPdf ? "Replace PDF" : "Upload PDF"}</Label>
                  <Input type="file" accept=".pdf" onChange={(e) => setPdfFile(e.target.files?.[0] || null)} />
                  <p className="text-xs text-muted-foreground">Upload the magazine PDF (max 200MB)</p>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>

        <div className="mt-6 flex justify-end gap-3">
          <Button variant="outline" asChild>
            <Link href="/dashboard/magazine/issues">Cancel</Link>
          </Button>
          <Button type="submit" disabled={isSubmitting}>
            {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Update Issue
          </Button>
        </div>
      </form>
    </div>
  );
}
