'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useToast } from '@/components/ui/use-toast';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { User } from 'lucide-react';
import { useTheme } from 'next-themes';

interface MahasiswaProfile {
  nim: string;
  nama: string;
  jk: 'Pria' | 'Wanita';
  agama: string;
  kabupaten: string;
  provinsi: string;
  jenis_pendaftaran: string;
  status_beasiswa: 'YA' | 'TIDAK';
  tahun_angkatan: string;
  ipk: number | null;
  prestasi: 'YA' | 'TIDAK';
  status_kuliah: string;
}

export default function ProfilePage() {
  const [profile, setProfile] = useState<MahasiswaProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const { toast } = useToast();
  const router = useRouter();
  const { theme } = useTheme();

  useEffect(() => {
    const fetchProfile = async () => {
      try {
        console.log('Fetching profile data...');
        const response = await fetch('/api/mahasiswa/profile');
        console.log('Profile response status:', response.status);
        
        if (response.status === 401) {
          toast({
            variant: "destructive",
            title: "Akses Ditolak",
            description: "Silakan login terlebih dahulu untuk mengakses halaman ini.",
          });
          router.push('/');
          return;
        }

        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.error || 'Failed to fetch profile data');
        }

        const data = await response.json();
        console.log('Profile data received:', data);
        setProfile(data);
      } catch (error) {
        console.error('Error fetching profile:', error);
        toast({
          variant: "destructive",
          title: "Error",
          description: error instanceof Error ? error.message : "Gagal memuat data profil. Silakan coba lagi nanti.",
        });
      } finally {
        setLoading(false);
      }
    };

    fetchProfile();
  }, [toast, router]);

  if (loading) {
    return (
      <div className="container mx-auto p-4 max-w-2xl">
        <Card className="border shadow-sm bg-white dark:bg-slate-900">
          <CardHeader className="border-b py-3 bg-white dark:bg-slate-900 text-black dark:text-white">
            <CardTitle className="text-lg">Profil Mahasiswa</CardTitle>
          </CardHeader>
          <CardContent className="p-4">
            <div className="space-y-3">
              {[...Array(8)].map((_, i) => (
                <div key={i} className="flex items-center gap-2">
                  <Skeleton className="h-3 w-[80px]" />
                  <Skeleton className="h-3 w-[140px]" />
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (!profile) {
    return (
      <div className="container mx-auto p-4 max-w-2xl">
        <Card className="border shadow-sm">
          <CardHeader className="border-b bg-muted/30 py-3">
            <CardTitle className="text-lg">Profil Mahasiswa</CardTitle>
          </CardHeader>
          <CardContent className="p-4">
            <div className="text-center text-muted-foreground text-sm py-4">
              Data profil tidak tersedia
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  // Format IPK value
  const formatIPK = (ipk: number | null): string => {
    if (ipk === null || ipk === undefined) return '-';
    return Number(ipk).toFixed(2);
  };

  return (
    <div className="container mx-auto p-4 w-full">
      <Card className="gap-0 bg-white dark:bg-slate-900 border shadow-sm">
        <CardHeader className="border-b py-2">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center">
              <User className="h-5 w-5 text-primary" />
            </div>
            <div>
              <CardTitle className="text-base font-medium text-black dark:text-white">{profile.nama}</CardTitle>
              <p className="text-xs text-muted-foreground">{profile.nim}</p>
            </div>
          </div>
        </CardHeader>
        <CardContent className="py-2 px-4">
          <div className="space-y-1 text-sm text-black dark:text-white">
            <div className="py-1.5 border-b">
              <div className="text-muted-foreground">Jenis Kelamin</div>
              <div>{profile.jk}</div>
            </div>
            <div className="py-1.5 border-b">
              <div className="text-muted-foreground">Agama</div>
              <div>{profile.agama}</div>
            </div>
            <div className="py-1.5 border-b">
              <div className="text-muted-foreground">Kabupaten</div>
              <div>{profile.kabupaten}</div>
            </div>
            <div className="py-1.5 border-b">
              <div className="text-muted-foreground">Provinsi</div>
              <div>{profile.provinsi}</div>
            </div>
            <div className="py-1.5 border-b">
              <div className="text-muted-foreground">Jenis Pendaftaran</div>
              <div>{profile.jenis_pendaftaran}</div>
            </div>
            <div className="py-1.5 border-b">
              <div className="text-muted-foreground">Tahun Angkatan</div>
              <div>{profile.tahun_angkatan}</div>
            </div>
            <div className="py-1.5 border-b">
              <div className="text-muted-foreground">IPK</div>
              <div>{formatIPK(profile.ipk)}</div>
            </div>
            <div className="py-1.5">
              <div className="text-muted-foreground">Status Kuliah</div>
              <div>{profile.status_kuliah || '-'}</div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
