'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, Trophy, Award } from 'lucide-react';
import { useTheme } from 'next-themes';

interface PrestasiMahasiswa {
  nama_prestasi: string;
  jenis_prestasi: string;
  tingkat_prestasi: string;
  peringkat: string;
  tanggal_prestasi: string;
}

interface BeasiswaMahasiswa {
  nama_beasiswa: string;
  sumber_beasiswa: string;
  jenis_beasiswa: string;
  beasiswa_status: string;
}

interface MahasiswaProfile {
  // Data Mahasiswa
  nama: string;
  nim: string;
  tahun_angkatan: string;
  jk: 'Pria' | 'Wanita';
  jenis_pendaftaran: string;
  ipk: number | null;
  agama: string;
  kabupaten: string;
  provinsi: string;
  
  // Status Mahasiswa
  status_kuliah: string;
  semester: string;
  
  // Prestasi Mahasiswa
  prestasi: PrestasiMahasiswa[];
  
  // Beasiswa Mahasiswa
  beasiswa: BeasiswaMahasiswa[];
}

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-4xl space-y-4">
        {[...Array(3)].map((_, i) => (
          <Card key={i} 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">
              <Skeleton className="h-6 w-[200px]" />
            </CardHeader>
            <CardContent className="p-4">
              <div className="space-y-3">
                {[...Array(8)].map((_, j) => (
                  <div key={j} 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-4xl">
        <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);
  };

  // Get first prestasi or create empty object
  const firstPrestasi = profile.prestasi.length > 0 ? profile.prestasi[0] : {
    nama_prestasi: '-',
    jenis_prestasi: '-',
    tingkat_prestasi: '-',
    peringkat: '-',
    tanggal_prestasi: '-'
  };

  // Get first beasiswa or create empty object
  const firstBeasiswa = profile.beasiswa.length > 0 ? profile.beasiswa[0] : {
    nama_beasiswa: '-',
    sumber_beasiswa: '-',
    jenis_beasiswa: '-',
    beasiswa_status: '-'
  };

  return (
    <div className="container mx-auto p-4 w-full max-w-4xl space-y-4">
      {/* Data Mahasiswa */}
      <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">Data Mahasiswa</CardTitle>
            </div>
          </div>
        </CardHeader>
        <CardContent className="py-2 px-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-black dark:text-white">
            <div className="space-y-1">
              <div className="py-1.5 border-b">
                <div className="text-muted-foreground">Nama Lengkap</div>
                <div>{profile.nama}</div>
              </div>
              <div className="py-1.5 border-b">
                <div className="text-muted-foreground">NIM</div>
                <div>{profile.nim}</div>
              </div>
              <div className="py-1.5 border-b">
                <div className="text-muted-foreground">Status Kuliah</div>
                <div>{profile.status_kuliah}</div>
              </div>
              <div className="py-1.5 border-b">
                <div className="text-muted-foreground">Semester</div>
                <div>{profile.semester}</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">Jenis Kelamin</div>
                <div>{profile.jk}</div>
              </div>
            </div>
            <div className="space-y-1">
              <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">IPK</div>
                <div>{formatIPK(profile.ipk)}</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">
                <div className="text-muted-foreground">Provinsi</div>
                <div>{profile.provinsi}</div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Prestasi Mahasiswa */}
      <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-yellow-100 dark:bg-yellow-900/20 flex items-center justify-center">
              <Trophy className="h-5 w-5 text-yellow-600 dark:text-yellow-400" />
            </div>
            <div>
              <CardTitle className="text-base font-medium text-black dark:text-white">Prestasi Mahasiswa</CardTitle>
            </div>
          </div>
        </CardHeader>
        <CardContent className="py-2 px-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-black dark:text-white">
            <div className="space-y-1">
              <div className="py-1.5 border-b">
                <div className="text-muted-foreground">Nama Prestasi</div>
                <div>{firstPrestasi.nama_prestasi}</div>
              </div>
              <div className="py-1.5 border-b">
                <div className="text-muted-foreground">Jenis Prestasi</div>
                <div>{firstPrestasi.jenis_prestasi}</div>
              </div>
              <div className="py-1.5 border-b">
                <div className="text-muted-foreground">Tingkat Prestasi</div>
                <div>{firstPrestasi.tingkat_prestasi}</div>
              </div>
            </div>
            <div className="space-y-1">
              <div className="py-1.5 border-b">
                <div className="text-muted-foreground">Peringkat</div>
                <div>{firstPrestasi.peringkat}</div>
              </div>
              <div className="py-1.5">
                <div className="text-muted-foreground">Tanggal Prestasi</div>
                <div>{firstPrestasi.tanggal_prestasi}</div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Beasiswa Mahasiswa */}
      <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-green-100 dark:bg-green-900/20 flex items-center justify-center">
              <Award className="h-5 w-5 text-green-600 dark:text-green-400" />
            </div>
            <div>
              <CardTitle className="text-base font-medium text-black dark:text-white">Beasiswa Mahasiswa</CardTitle>
            </div>
          </div>
        </CardHeader>
        <CardContent className="py-2 px-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-black dark:text-white">
            <div className="space-y-1">
              <div className="py-1.5 border-b">
                <div className="text-muted-foreground">Nama Beasiswa</div>
                <div>{firstBeasiswa.nama_beasiswa}</div>
              </div>
              <div className="py-1.5 border-b">
                <div className="text-muted-foreground">Sumber Beasiswa</div>
                <div>{firstBeasiswa.sumber_beasiswa}</div>
              </div>
            </div>
            <div className="space-y-1">
              <div className="py-1.5 border-b">
                <div className="text-muted-foreground">Jenis Beasiswa</div>
                <div>{firstBeasiswa.jenis_beasiswa}</div>
              </div>
              <div className="py-1.5">
                <div className="text-muted-foreground">Status Beasiswa</div>
                <div>{firstBeasiswa.beasiswa_status}</div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
