"use client";

import { useState } from "react";
import Image from "next/image";
import { motion, AnimatePresence } from "framer-motion";
import {
  Calendar,
  MapPin,
  Clock,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";
import Link from "next/link";

interface ProjectImage {
  id: string;
  url: string;
  image?: string;
}

interface Project {
  id: string;
  name: string;
  description: string;
  location?: string;
  start_date?: string;
  end_date?: string;
  status?: string;
  client?: string;
  category_id: string;
  image?: string;
  images?: ProjectImage[];
  details?: string;
  features?: string[];
}

interface ProjectDetailProps {
  project: Project;
}

export default function ProjectDetail({ project }: ProjectDetailProps) {
  console.log(project);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);

  const projectImages = project.images || [];
  if (
    project.image &&
    !projectImages.some((img) => img.url === project.image)
  ) {
    projectImages.unshift({ id: "main", url: project.image });
  }

  const nextImage = () => {
    setCurrentImageIndex((prev) =>
      prev === projectImages.length - 1 ? 0 : prev + 1,
    );
  };

  const prevImage = () => {
    setCurrentImageIndex((prev) =>
      prev === 0 ? projectImages.length - 1 : prev - 1,
    );
  };

  // Format date to readable format
  const formatDate = (dateString?: string) => {
    if (!dateString) return "N/A";
    return new Date(dateString).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  };

  // Parse features from string if needed
  const projectFeatures =
    project.features ||
    (project.details
      ? project.details
          .split("\n")
          .filter((line) => line.trim().startsWith("-"))
      : []);

  // const truncateText = (html: string, maxLength: number) => {
  //   return truncate(html, maxLength);
  // };

  return (
    <div className="bg-white rounded-xl shadow-lg overflow-hidden">
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        {/* Project Images */}
        <div className="relative overflow-hidden rounded-t-xl lg:rounded-l-xl lg:rounded-tr-none">
          <div className="relative h-[300px] sm:h-[400px] lg:h-full w-full">
            {projectImages.length > 0 ? (
              <AnimatePresence mode="wait">
                <motion.div
                  key={currentImageIndex}
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                  transition={{ duration: 0.5 }}
                  className="absolute inset-0"
                >
                  <Image
                    src={
                      `${process.env.NEXT_PUBLIC_API_URL}/storage/${projectImages[currentImageIndex].image}` ||
                      "/placeholder.svg"
                    }
                    alt={`${project.name} - Image ${currentImageIndex + 1}`}
                    fill
                    className="object-cover"
                  />
                </motion.div>
              </AnimatePresence>
            ) : (
              <div className="absolute inset-0 bg-gray-200 flex items-center justify-center">
                <p className="text-gray-500">No images available</p>
              </div>
            )}

            {/* Image navigation */}
            {projectImages.length > 1 && (
              <>
                <button
                  onClick={prevImage}
                  className="absolute left-4 top-1/2 transform -translate-y-1/2 bg-black/50 text-white p-2 rounded-full hover:bg-black/70 transition-colors"
                  aria-label="Previous image"
                >
                  <ChevronLeft size={20} />
                </button>
                <button
                  onClick={nextImage}
                  className="absolute right-4 top-1/2 transform -translate-y-1/2 bg-black/50 text-white p-2 rounded-full hover:bg-black/70 transition-colors"
                  aria-label="Next image"
                >
                  <ChevronRight size={20} />
                </button>
                <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 flex space-x-2">
                  {projectImages.map((_, index) => (
                    <button
                      key={index}
                      onClick={() => setCurrentImageIndex(index)}
                      className={`w-2 h-2 rounded-full ${index === currentImageIndex ? "bg-white" : "bg-white/50"}`}
                      aria-label={`Go to image ${index + 1}`}
                    />
                  ))}
                </div>
              </>
            )}
          </div>
        </div>

        {/* Project Details */}
        <div className="p-6 lg:p-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-4">
            {project.name}
          </h1>

          <div className="w-20 h-1 bg-gradient-to-r from-orange-500 to-red-500 mb-6 rounded-full"></div>

          <div
            className="text-gray-700 flex-grow mb-8 leading-relaxed break-words"
            style={{
              WebkitBoxOrient: "vertical",
            }}
            dangerouslySetInnerHTML={{
              __html: project.description,
            }}
          />

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
            {project.location && (
              <div className="flex items-center">
                <MapPin className="text-orange-500 mr-2 h-5 w-5 flex-shrink-0" />
                <div>
                  <p className="text-sm text-gray-500">Location</p>
                  <p className="font-medium">{project.location}</p>
                </div>
              </div>
            )}

            {project.client && (
              <div className="flex items-center">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  className="text-orange-500 mr-2 h-5 w-5 flex-shrink-0"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"
                  />
                </svg>
                <div>
                  <p className="text-sm text-gray-500">Client</p>
                  <p className="font-medium">{project.client}</p>
                </div>
              </div>
            )}

            {project.start_date && (
              <div className="flex items-center">
                <Calendar className="text-orange-500 mr-2 h-5 w-5 flex-shrink-0" />
                <div>
                  <p className="text-sm text-gray-500">Start Date</p>
                  <p className="font-medium">
                    {formatDate(project.start_date)}
                  </p>
                </div>
              </div>
            )}

            {project.status && (
              <div className="flex items-center">
                <Clock className="text-orange-500 mr-2 h-5 w-5 flex-shrink-0" />
                <div>
                  <p className="text-sm text-gray-500">Status</p>
                  <p className="font-medium">
                    <span
                      className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                        project.status.toLowerCase() === "completed"
                          ? "bg-green-100 text-green-800"
                          : project.status.toLowerCase() === "in progress"
                            ? "bg-blue-100 text-blue-800"
                            : "bg-yellow-100 text-yellow-800"
                      }`}
                    >
                      {project.status}
                    </span>
                  </p>
                </div>
              </div>
            )}
          </div>

          {projectFeatures.length > 0 && (
            <div className="mb-6">
              <h3 className="text-lg font-semibold mb-3">Project Features</h3>
              <ul className="space-y-2">
                {projectFeatures.map((feature, index) => (
                  <li key={index} className="flex items-start">
                    <svg
                      className="h-5 w-5 text-orange-500 mr-2 mt-0.5 flex-shrink-0"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M5 13l4 4L19 7"
                      />
                    </svg>
                    <span className="text-gray-700">
                      {typeof feature === "string"
                        ? feature.replace(/^-\s*/, "")
                        : feature}
                    </span>
                  </li>
                ))}
              </ul>
            </div>
          )}

          {project.details && !project.features && (
            <div className="mb-6">
              <h3 className="text-lg font-semibold mb-3">Additional Details</h3>
              <div className="prose prose-orange max-w-none text-gray-700">
                {project.details
                  .split("\n")
                  .map((paragraph, index) =>
                    !paragraph.trim().startsWith("-") && paragraph.trim() ? (
                      <p key={index}>{paragraph}</p>
                    ) : null,
                  )}
              </div>
            </div>
          )}

          <div className="mt-8">
            <Link href="/contact">
              <motion.button
                whileHover={{
                  scale: 1.05,
                  boxShadow: "0 10px 25px -5px rgba(249, 115, 22, 0.4)",
                }}
                whileTap={{ scale: 0.95 }}
                className="px-6 py-3 bg-gradient-to-r from-orange-500 to-red-500 text-white font-medium rounded-lg shadow-md hover:shadow-lg transition-all"
              >
                Request Similar Project
              </motion.button>
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
