"use client";
import { useEffect, useState } from "react";
import { use } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  CheckCircle2,
  Loader2,
  Award,
  AlertCircle,
  ArrowLeft,
  Mail,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { lookupCertificate, type Certificate } from "@/services/certificates";

export default function VerifyCertificateDetailPage({
  params,
}: {
  params: Promise<{ certificate_no: string }>;
}) {
  const router = useRouter();
  const { certificate_no } = use(params);
  const [certificate, setCertificate] = useState<Certificate | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchCertificate = async () => {
      try {
        setLoading(true);
        setError(null);
        const cert = await lookupCertificate(decodeURIComponent(certificate_no));
        setCertificate(cert);
      } catch (err: any) {
        if (err?.response?.status === 404) {
          setError("Certificate not found. Please check the certificate number and try again.");
        } else {
          setError("An error occurred while retrieving the certificate. Please try again.");
        }
        setCertificate(null);
      } finally {
        setLoading(false);
      }
    };

    fetchCertificate();
  }, [certificate_no]);

  const formatDate = (dateString: string) => {
    try {
      return new Date(dateString).toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "numeric",
      });
    } catch {
      return dateString;
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-primary flex flex-col items-center justify-center px-6">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="w-8 h-8 text-accent animate-spin" />
          <p className="text-primary-foreground/60 text-sm">
            Verifying certificate...
          </p>
        </div>
      </div>
    );
  }

  if (error || !certificate) {
    return (
      <div className="min-h-screen bg-primary flex flex-col items-center justify-center px-6">
        <div className="w-full max-w-md text-center">
          <div className="w-14 h-14 rounded-full bg-destructive/20 flex items-center justify-center mx-auto mb-6">
            <AlertCircle className="w-7 h-7 text-destructive" />
          </div>
          <h1 className="text-2xl font-bold text-primary-foreground">
            Certificate Not Found
          </h1>
          <p className="text-primary-foreground/60 mt-2 text-sm">
            {error || "The certificate could not be found in our system."}
          </p>

          <Button
            onClick={() => router.push("/certificates/verify")}
            className="mt-6 bg-accent text-accent-foreground"
          >
            Try Another Certificate
          </Button>
        </div>
      </div>
    );
  }

  const isExpired = new Date(certificate.next_due_date) < new Date();

  return (
    <div className="min-h-screen bg-gradient-to-b from-primary/95 to-primary pt-20 pb-20 px-6">
      <div className="max-w-2xl mx-auto">
        

        {/* Main card */}
        <div className="bg-white rounded-2xl shadow-2xl border mt-20 overflow-hidden">
          {/* Header with verified badge */}
          <div className="bg-gradient-to-r from-green-500 to-green-600 px-6 sm:px-8 py-8">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-12 h-12 rounded-full bg-white/20 flex items-center justify-center">
                <CheckCircle2 className="w-6 h-6 text-white" />
              </div>
              <div>
                <p className="text-white/90 text-sm font-medium">Certificate Verified</p>
                <h1 className="text-2xl font-bold text-white">
                  {certificate.certificate_no}
                </h1>
                <span
                  className={`inline-flex items-center gap-1.5 mt-2 px-3 py-1 rounded-full text-xs font-semibold ${
                    isExpired
                      ? "bg-red-500/30 text-red-100"
                      : "bg-white/20 text-white"
                  }`}
                >
                  <span className={`w-1.5 h-1.5 rounded-full ${isExpired ? "bg-red-300" : "bg-green-300"}`} />
                  {isExpired ? "Expired" : "Active"}
                </span>
              </div>
            </div>
          </div>

          {/* Content */}
          <div className="px-6 sm:px-8 py-8 space-y-8">
            {/* Key Information */}
            <div>
              <h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground mb-4">
                Equipment Information
              </h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                <div>
                  <p className="text-sm text-muted-foreground mb-1">Equipment</p>
                  <p className="text-lg font-semibold text-foreground">
                    {certificate.equipment}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground mb-1">ID Number</p>
                  <p className="text-lg font-semibold text-foreground font-mono">
                    {certificate.id_number}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground mb-1">Location</p>
                  <p className="text-lg font-semibold text-foreground">
                    {certificate.location}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground mb-1">Company</p>
                  <p className="text-lg font-semibold text-foreground">
                    {certificate.company}
                  </p>
                </div>
              </div>
            </div>

            {/* Inspection Dates */}
            <div className="border-t border-border pt-8">
              <h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground mb-4">
                Inspection Dates
              </h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                <div className="bg-blue-50 dark:bg-blue-950/30 rounded-lg p-4">
                  <p className="text-xs text-blue-600 dark:text-blue-400 font-medium uppercase tracking-wider mb-1">
                    Inspection Date
                  </p>
                  <p className="text-lg font-semibold text-foreground">
                    {formatDate(certificate.inspection_date)}
                  </p>
                </div>
                <div className="bg-green-50 dark:bg-green-950/30 rounded-lg p-4">
                  <p className="text-xs text-green-600 dark:text-green-400 font-medium uppercase tracking-wider mb-1">
                    Next Due Date
                  </p>
                  <p className="text-lg font-semibold text-foreground">
                    {formatDate(certificate.next_due_date)}
                  </p>
                </div>
              </div>
            </div>

            {/* Examination Results */}
            {certificate.examination && (
              <div className="border-t border-border pt-8">
                <h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground mb-3">
                  Examination Results
                </h2>
                <div className="bg-secondary rounded-lg p-4">
                  <p className="text-foreground whitespace-pre-wrap">
                    {certificate.examination}
                  </p>
                </div>
              </div>
            )}

            {/* Remarks */}
            {certificate.remark && (
              <div className="border-t border-border pt-8">
                <h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground mb-3">
                  Remarks
                </h2>
                <div className="bg-secondary rounded-lg p-4">
                  <p className="text-foreground whitespace-pre-wrap">
                    {certificate.remark}
                  </p>
                </div>
              </div>
            )}

            {/* Metadata */}
            <div className="border-t border-border pt-8">
              <h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground mb-4">
                Record Information
              </h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
                <div>
                  <p className="text-muted-foreground mb-1">Created</p>
                  <p className="text-foreground">
                    {formatDate(certificate.created_at)}
                  </p>
                </div>
                <div>
                  <p className="text-muted-foreground mb-1">Last Updated</p>
                  <p className="text-foreground">
                    {formatDate(certificate.updated_at)}
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* Footer action */}
          <div className="border-t border-border bg-secondary/50 px-6 sm:px-8 py-6 flex flex-col sm:flex-row gap-3">
            <Button
              onClick={() => router.push("/certificates/verify")}
              variant="outline"
              className="flex-1"
            >
              Verify Another Certificate
            </Button>
            <Button
              onClick={() => {
                const to = "verification@petrobasegroup.com";
                const subject = encodeURIComponent(`REQUEST FOR CERTIFICATE COPY - ${certificate.certificate_no}`);
                const body = encodeURIComponent(
                  `Hello,\n\nI would like to request a copy of certificate number: ${certificate.certificate_no}.\n\nThank you.`
                );
                window.location.href = `mailto:${to}?subject=${subject}&body=${body}`;
              }}
              variant="outline"
              className="flex-1 gap-2"
            >
              <Mail className="w-4 h-4" />
              Request a Copy
            </Button>
            <Link href="/" className="flex-1">
              <Button className="w-full bg-primary text-primary-foreground">
                Back to Home
              </Button>
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
