"use client";

import { useState } from "react";
import { useAuth } from "@/lib/auth-context";
import { getGuideById, mockCertifications } from "@/lib/mock-data";
import { CERTIFICATION_TYPES } from "@/lib/types";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { DashboardBreadcrumb } from "@/components/dashboard/dashboard-breadcrumb";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  Award,
  Plus,
  Clock,
  CheckCircle2,
  AlertCircle,
  Calendar,
  Loader2,
} from "lucide-react";

export default function CertificationsPage() {
  const { user } = useAuth();
  const guide = user?.guideId ? getGuideById(user.guideId) : null;

  const approvedCerts =
    guide?.certifications.filter((c) => c.status === "approved") || [];
  const pendingCerts = mockCertifications.filter(
    (c) => c.guideId === user?.guideId && c.status === "pending",
  );

  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [newCertType, setNewCertType] = useState("");

  const handleApply = async () => {
    setIsSubmitting(true);
    await new Promise((resolve) => setTimeout(resolve, 1500));
    setIsSubmitting(false);
    setIsDialogOpen(false);
    setNewCertType("");
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "approved":
        return (
          <Badge className="rounded-full bg-green-50 px-3 py-1 font-semibold text-green-700">
            <CheckCircle2 className="h-3 w-3 mr-1" />
            Active
          </Badge>
        );
      case "pending":
        return (
          <Badge className="rounded-full bg-[var(--theme-surface-strong)] px-3 py-1 font-semibold text-[var(--theme-primary)]">
            <Clock className="h-3 w-3 mr-1" />
            Pending
          </Badge>
        );
      case "expired":
        return (
          <Badge variant="destructive">
            <AlertCircle className="h-3 w-3 mr-1" />
            Expired
          </Badge>
        );
      default:
        return <Badge variant="outline">{status}</Badge>;
    }
  };

  return (
    <div className="space-y-5">
      <DashboardBreadcrumb current="Certifications" />

      <div className="flex flex-col gap-3 rounded-3xl border border-[var(--theme-border)] bg-white p-5 shadow-sm sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-black text-foreground">
            Certifications
          </h1>
          <p className="mt-1 text-sm font-medium text-muted-foreground">
            Manage your professional certifications
          </p>
        </div>
        <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              Apply for Certification
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Apply for Certification</DialogTitle>
              <DialogDescription>
                Select the certification you want to apply for
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4 py-4">
              <div className="space-y-2">
                <Label htmlFor="certType">Certification Type</Label>
                <Select value={newCertType} onValueChange={setNewCertType}>
                  <SelectTrigger>
                    <SelectValue placeholder="Select certification" />
                  </SelectTrigger>
                  <SelectContent>
                    {CERTIFICATION_TYPES.map((cert) => (
                      <SelectItem key={cert.value} value={cert.value}>
                        {cert.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="document">Supporting Document</Label>
                <Input id="document" type="file" />
                <p className="text-xs text-muted-foreground">
                  Upload any relevant certificates or training completion
                  documents
                </p>
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
                Cancel
              </Button>
              <Button
                onClick={handleApply}
                disabled={!newCertType || isSubmitting}
              >
                {isSubmitting ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    Submitting...
                  </>
                ) : (
                  "Submit Application"
                )}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      {/* Active Certifications */}
      <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
        <CardHeader className="px-5 pt-5">
          <CardTitle className="text-xl font-black">
            Active Certifications
          </CardTitle>
          <CardDescription>
            Your approved and valid certifications
          </CardDescription>
        </CardHeader>
        <CardContent className="p-5 pt-2">
          {approvedCerts.length > 0 ? (
            <div className="space-y-4">
              {approvedCerts.map((cert) => (
                <div
                  key={cert.id}
                  className="flex items-center justify-between rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-4"
                >
                  <div className="flex items-center gap-4">
                    <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-[var(--theme-surface-strong)]">
                      <Award className="h-6 w-6 text-[var(--theme-primary)]" />
                    </div>
                    <div>
                      <h4 className="font-medium text-foreground">
                        {cert.name}
                      </h4>
                      <div className="flex items-center gap-2 text-sm text-muted-foreground">
                        <Calendar className="h-3.5 w-3.5" />
                        <span>
                          Valid until{" "}
                          {cert.expiresAt
                            ? new Date(cert.expiresAt).toLocaleDateString()
                            : "N/A"}
                        </span>
                      </div>
                    </div>
                  </div>
                  {getStatusBadge(cert.status)}
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8">
              <Award className="h-12 w-12 mx-auto mb-4 text-muted-foreground" />
              <p className="text-muted-foreground">No active certifications</p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Pending Applications */}
      {pendingCerts.length > 0 && (
        <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
          <CardHeader className="px-5 pt-5">
            <CardTitle className="text-xl font-black">
              Pending Applications
            </CardTitle>
            <CardDescription>Applications under review</CardDescription>
          </CardHeader>
          <CardContent className="p-5 pt-2">
            <div className="space-y-4">
              {pendingCerts.map((cert) => (
                <div
                  key={cert.id}
                  className="flex items-center justify-between rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-4"
                >
                  <div className="flex items-center gap-4">
                    <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-[var(--theme-surface-strong)]">
                      <Clock className="h-6 w-6 text-[var(--theme-primary)]" />
                    </div>
                    <div>
                      <h4 className="font-medium text-foreground">
                        {cert.name}
                      </h4>
                      <p className="text-sm text-muted-foreground">
                        Applied on{" "}
                        {new Date(cert.appliedAt).toLocaleDateString()}
                      </p>
                    </div>
                  </div>
                  {getStatusBadge(cert.status)}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Available Certifications Info */}
      <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
        <CardHeader className="px-5 pt-5">
          <CardTitle className="text-xl font-black">
            Available Certifications
          </CardTitle>
          <CardDescription>Certifications you can apply for</CardDescription>
        </CardHeader>
        <CardContent className="p-5 pt-2">
          <div className="grid sm:grid-cols-2 gap-4">
            {CERTIFICATION_TYPES.map((cert) => (
              <div
                key={cert.value}
                className="rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-4 transition-all hover:-translate-y-0.5 hover:border-[var(--theme-secondary)]/35 hover:shadow-lg hover:shadow-[var(--theme-secondary)]/10"
              >
                <div className="flex items-start gap-3">
                  <Award className="mt-0.5 h-5 w-5 text-[var(--theme-primary)]" />
                  <div>
                    <h4 className="font-medium text-foreground">
                      {cert.label}
                    </h4>
                    <p className="text-sm text-muted-foreground mt-1">
                      Specialized certification for {cert.label.toLowerCase()}{" "}
                      guiding services.
                    </p>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
