import React, { useState, useMemo } from 'react';
import { Proposal, ProgramType, UserRole } from '../types';
import { formatRupiah, getProposalStatusBadge } from '../data/storage';
import { RESEARCH_SCHEMES, COMMUNITY_SCHEMES, FOCUS_AREAS } from '../data/initialData';
import {
  Search,
  Filter,
  BookOpen,
  Users,
  PlusCircle,
  FileText,
  CheckCircle2,
  AlertCircle,
  Clock,
  ExternalLink,
  ChevronRight,
  Eye,
  Award,
  Layers,
  LayoutGrid,
  List,
  Building,
  Check,
  X
} from 'lucide-react';

interface ProposalListViewProps {
  programType: ProgramType;
  proposals: Proposal[];
  userRole: UserRole;
  onSelectProposal: (proposal: Proposal) => void;
  onOpenNewProposal: () => void;
  onOpenReviewModal: (proposal: Proposal) => void;
  onOpenReportModal: (proposal: Proposal) => void;
  onUpdateStatus: (proposalId: string, newStatus: Proposal['status'], approvedBudget?: number) => void;
}

export const ProposalListView: React.FC<ProposalListViewProps> = ({
  programType,
  proposals,
  userRole,
  onSelectProposal,
  onOpenNewProposal,
  onOpenReviewModal,
  onOpenReportModal,
  onUpdateStatus,
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedStatus, setSelectedStatus] = useState<string>('ALL');
  const [selectedScheme, setSelectedScheme] = useState<string>('ALL');
  const [selectedFocus, setSelectedFocus] = useState<string>('ALL');
  const [viewMode, setViewMode] = useState<'grid' | 'table'>('table');

  const isResearch = programType === 'penelitian';
  const availableSchemes = isResearch ? RESEARCH_SCHEMES : COMMUNITY_SCHEMES;

  // Filtered list
  const filteredProposals = useMemo(() => {
    return proposals.filter((p) => {
      // Must match program type
      if (p.type !== programType) return false;

      // Status filter
      if (selectedStatus !== 'ALL' && p.status !== selectedStatus) return false;

      // Scheme filter
      if (selectedScheme !== 'ALL' && p.scheme !== selectedScheme) return false;

      // Focus area filter
      if (selectedFocus !== 'ALL' && p.focusArea !== selectedFocus) return false;

      // Text search
      if (searchQuery.trim()) {
        const q = searchQuery.toLowerCase();
        const matchTitle = p.title.toLowerCase().includes(q);
        const matchLeader = p.leader.name.toLowerCase().includes(q) || p.leader.nidn.includes(q);
        const matchCode = p.code.toLowerCase().includes(q);
        const matchKeywords = p.keywords.some((k) => k.toLowerCase().includes(q));
        const matchFaculty = p.leader.faculty.toLowerCase().includes(q);
        const matchPartner = p.partner?.name.toLowerCase().includes(q);
        if (!matchTitle && !matchLeader && !matchCode && !matchKeywords && !matchFaculty && !matchPartner) {
          return false;
        }
      }

      return true;
    });
  }, [proposals, programType, selectedStatus, selectedScheme, selectedFocus, searchQuery]);

  // Status breakdown counts
  const countAll = proposals.filter((p) => p.type === programType).length;
  const countInReview = proposals.filter((p) => p.type === programType && (p.status === 'IN_REVIEW' || p.status === 'SUBMITTED')).length;
  const countApproved = proposals.filter(
    (p) => p.type === programType && ['APPROVED', 'PROGRESS_REPORTED', 'FINAL_REPORTED', 'COMPLETED'].includes(p.status)
  ).length;
  const countCompleted = proposals.filter((p) => p.type === programType && p.status === 'COMPLETED').length;

  return (
    <div className="space-y-6">
      {/* Header Banner */}
      <div className="bg-white rounded-xl p-6 border border-slate-200 shadow-xs flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <span
              className={`w-8 h-8 rounded-lg flex items-center justify-center text-white ${
                isResearch ? 'bg-blue-600' : 'bg-emerald-600'
              }`}
            >
              {isResearch ? <BookOpen className="w-5 h-5" /> : <Users className="w-5 h-5" />}
            </span>
            <h1 className="text-xl font-bold text-slate-900">
              {isResearch ? 'Manajemen Usulan Penelitian' : 'Manajemen Usulan Pengabdian kepada Masyarakat (PKM)'}
            </h1>
          </div>
          <p className="text-xs text-slate-500 max-w-2xl">
            {isResearch
              ? 'Kelola pengajuan proposal riset dasar, terapan, dan pengembangan dosen sesuai renstra riset dan capaian TKT.'
              : 'Tata kelola proposal pengabdian kemitraan masyarakat (PKM), desa binaan, dan hilirisasi teknologi tepat guna ke masyarakat.'}
          </p>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={onOpenNewProposal}
            className={`text-white text-sm font-semibold px-4 py-2.5 rounded-lg flex items-center gap-2 transition-colors cursor-pointer shadow-xs ${
              isResearch ? 'bg-blue-600 hover:bg-blue-700' : 'bg-emerald-600 hover:bg-emerald-700'
            }`}
          >
            <PlusCircle className="w-4 h-4" />
            <span>Usulan {isResearch ? 'Penelitian' : 'Pengabdian'} Baru</span>
          </button>
        </div>
      </div>

      {/* Quick Status Pill Filters */}
      <div className="flex flex-wrap items-center gap-2 text-xs">
        <button
          onClick={() => setSelectedStatus('ALL')}
          className={`px-3 py-1.5 rounded-lg font-medium transition-colors cursor-pointer border ${
            selectedStatus === 'ALL'
              ? 'bg-slate-900 text-white border-slate-900'
              : 'bg-white text-slate-600 border-slate-200 hover:bg-slate-50'
          }`}
        >
          Semua ({countAll})
        </button>

        <button
          onClick={() => setSelectedStatus('IN_REVIEW')}
          className={`px-3 py-1.5 rounded-lg font-medium transition-colors cursor-pointer border ${
            selectedStatus === 'IN_REVIEW'
              ? 'bg-amber-700 text-white border-amber-700'
              : 'bg-white text-amber-800 border-amber-200 hover:bg-amber-50'
          }`}
        >
          Dalam Review ({countInReview})
        </button>

        <button
          onClick={() => setSelectedStatus('APPROVED')}
          className={`px-3 py-1.5 rounded-lg font-medium transition-colors cursor-pointer border ${
            selectedStatus === 'APPROVED'
              ? 'bg-emerald-700 text-white border-emerald-700'
              : 'bg-white text-emerald-800 border-emerald-200 hover:bg-emerald-50'
          }`}
        >
          Didanai / Disetujui ({countApproved})
        </button>

        <button
          onClick={() => setSelectedStatus('PROGRESS_REPORTED')}
          className={`px-3 py-1.5 rounded-lg font-medium transition-colors cursor-pointer border ${
            selectedStatus === 'PROGRESS_REPORTED'
              ? 'bg-indigo-700 text-white border-indigo-700'
              : 'bg-white text-indigo-800 border-indigo-200 hover:bg-indigo-50'
          }`}
        >
          Monev 70% Berjalan
        </button>

        <button
          onClick={() => setSelectedStatus('COMPLETED')}
          className={`px-3 py-1.5 rounded-lg font-medium transition-colors cursor-pointer border ${
            selectedStatus === 'COMPLETED'
              ? 'bg-teal-700 text-white border-teal-700'
              : 'bg-white text-teal-800 border-teal-200 hover:bg-teal-50'
          }`}
        >
          Selesai & Luaran Valid ({countCompleted})
        </button>
      </div>

      {/* Search & Select Filters Bar */}
      <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs flex flex-col md:flex-row items-stretch md:items-center justify-between gap-3 text-xs">
        <div className="relative flex-1">
          <Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
          <input
            type="text"
            placeholder="Cari judul usulan, nama ketua / NIDN, kode berkas, atau mitra..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-9 pr-4 py-2 bg-slate-50 border border-slate-200 rounded-lg text-xs text-slate-900 focus:outline-hidden focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
          />
        </div>

        <div className="flex flex-wrap items-center gap-2">
          {/* Scheme Filter */}
          <select
            value={selectedScheme}
            onChange={(e) => setSelectedScheme(e.target.value)}
            className="bg-slate-50 border border-slate-200 rounded-lg px-2.5 py-2 text-slate-700 focus:outline-hidden text-xs"
          >
            <option value="ALL">Semua Skema</option>
            {availableSchemes.map((s) => (
              <option key={s} value={s}>
                {s}
              </option>
            ))}
          </select>

          {/* Focus Area Filter */}
          <select
            value={selectedFocus}
            onChange={(e) => setSelectedFocus(e.target.value)}
            className="bg-slate-50 border border-slate-200 rounded-lg px-2.5 py-2 text-slate-700 focus:outline-hidden text-xs max-w-[180px]"
          >
            <option value="ALL">Semua Bidang Fokus</option>
            {FOCUS_AREAS.map((f) => (
              <option key={f} value={f}>
                {f}
              </option>
            ))}
          </select>

          {/* View Mode Toggle */}
          <div className="border border-slate-200 rounded-lg p-0.5 flex bg-slate-50">
            <button
              onClick={() => setViewMode('table')}
              className={`p-1.5 rounded cursor-pointer ${
                viewMode === 'table' ? 'bg-white text-slate-900 shadow-2xs font-semibold' : 'text-slate-500'
              }`}
              title="Tampilan Tabel"
            >
              <List className="w-4 h-4" />
            </button>
            <button
              onClick={() => setViewMode('grid')}
              className={`p-1.5 rounded cursor-pointer ${
                viewMode === 'grid' ? 'bg-white text-slate-900 shadow-2xs font-semibold' : 'text-slate-500'
              }`}
              title="Tampilan Kartu"
            >
              <LayoutGrid className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* Results Count */}
      <div className="flex items-center justify-between text-xs text-slate-500 px-1">
        <span>Menampilkan {filteredProposals.length} dari total {countAll} usulan</span>
      </div>

      {/* Main Content: Table or Grid */}
      {filteredProposals.length === 0 ? (
        <div className="bg-white rounded-xl border border-dashed border-slate-300 p-12 text-center">
          <div className="w-12 h-12 rounded-full bg-slate-100 text-slate-400 mx-auto flex items-center justify-center mb-3">
            <AlertCircle className="w-6 h-6" />
          </div>
          <h3 className="text-sm font-semibold text-slate-900 mb-1">Tidak ada usulan yang cocok</h3>
          <p className="text-xs text-slate-500 max-w-sm mx-auto mb-4">
            Coba sesuaikan kata kunci pencarian atau bersihkan filter skema dan status yang aktif.
          </p>
          <button
            onClick={() => {
              setSearchQuery('');
              setSelectedStatus('ALL');
              setSelectedScheme('ALL');
              setSelectedFocus('ALL');
            }}
            className="text-xs text-blue-600 font-semibold hover:underline cursor-pointer"
          >
            Reset Semua Filter
          </button>
        </div>
      ) : viewMode === 'table' ? (
        /* TABLE VIEW */
        <div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-x-auto">
          <table className="w-full text-left text-xs border-collapse">
            <thead>
              <tr className="bg-slate-50/80 border-b border-slate-200 text-slate-600 font-semibold uppercase tracking-wider text-[10px]">
                <th className="py-3.5 px-4">Kode & Judul Usulan</th>
                <th className="py-3.5 px-4">Ketua Peneliti & Unit</th>
                <th className="py-3.5 px-4">Skema & Fokus</th>
                <th className="py-3.5 px-4">TKT</th>
                <th className="py-3.5 px-4">Anggaran</th>
                <th className="py-3.5 px-4">Status & Monev</th>
                <th className="py-3.5 px-4 text-right">Aksi</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-200 text-slate-700">
              {filteredProposals.map((prop) => {
                const badge = getProposalStatusBadge(prop.status);
                const hasReview = prop.reviews.length > 0;
                const hasOutputs = prop.actualOutputs.length > 0;

                return (
                  <tr
                    key={prop.id}
                    className="hover:bg-slate-50/60 transition-colors cursor-pointer group"
                    onClick={() => onSelectProposal(prop)}
                  >
                    {/* Title & Code */}
                    <td className="py-3.5 px-4 max-w-xs">
                      <div className="font-mono text-[10px] text-slate-500 mb-0.5">{prop.code}</div>
                      <div className="font-semibold text-slate-900 group-hover:text-blue-600 transition-colors line-clamp-2 leading-snug">
                        {prop.title}
                      </div>
                      {prop.partner && (
                        <div className="text-[11px] text-emerald-700 mt-1 flex items-center gap-1">
                          <Building className="w-3 h-3 shrink-0" />
                          <span className="truncate">Mitra: {prop.partner.name}</span>
                        </div>
                      )}
                    </td>

                    {/* Leader & Faculty */}
                    <td className="py-3.5 px-4 whitespace-nowrap">
                      <div className="font-semibold text-slate-900">{prop.leader.name}</div>
                      <div className="text-[11px] text-slate-500">NIDN: {prop.leader.nidn}</div>
                      <div className="text-[10px] text-slate-600">{prop.leader.department}</div>
                    </td>

                    {/* Scheme & Focus */}
                    <td className="py-3.5 px-4 max-w-[180px]">
                      <div className="font-medium text-slate-800 truncate" title={prop.scheme}>
                        {prop.scheme}
                      </div>
                      <div className="text-[10px] text-slate-500 truncate" title={prop.focusArea}>
                        {prop.focusArea}
                      </div>
                    </td>

                    {/* TKT */}
                    <td className="py-3.5 px-4 whitespace-nowrap">
                      <span className="font-semibold text-slate-800 bg-slate-100 px-2 py-0.5 rounded text-[11px]">
                        TKT {prop.tktCurrent} → {prop.tktTarget}
                      </span>
                    </td>

                    {/* Budget */}
                    <td className="py-3.5 px-4 whitespace-nowrap">
                      {prop.approvedBudget ? (
                        <div>
                          <div className="font-bold text-emerald-700">{formatRupiah(prop.approvedBudget)}</div>
                          <div className="text-[10px] text-slate-400 line-through">
                            {formatRupiah(prop.requestedBudget)}
                          </div>
                        </div>
                      ) : (
                        <div className="font-semibold text-slate-800">{formatRupiah(prop.requestedBudget)}</div>
                      )}
                    </td>

                    {/* Status badge & indicators */}
                    <td className="py-3.5 px-4 whitespace-nowrap">
                      <span className={`inline-flex items-center text-[10px] font-semibold px-2 py-0.5 rounded-full border ${badge.bg} ${badge.color} ${badge.border}`}>
                        {badge.label}
                      </span>

                      <div className="flex items-center gap-1.5 mt-1 text-[10px] text-slate-500">
                        {hasReview && (
                          <span className="text-amber-700 bg-amber-50 px-1 rounded flex items-center gap-0.5">
                            <CheckCircle2 className="w-2.5 h-2.5" /> Nilai: {prop.reviews[0].totalScore}
                          </span>
                        )}
                        {hasOutputs && (
                          <span className="text-indigo-700 bg-indigo-50 px-1 rounded flex items-center gap-0.5">
                            <Award className="w-2.5 h-2.5" /> {prop.actualOutputs.length} Luaran
                          </span>
                        )}
                      </div>
                    </td>

                    {/* Actions */}
                    <td className="py-3.5 px-4 text-right whitespace-nowrap" onClick={(e) => e.stopPropagation()}>
                      <div className="flex items-center justify-end gap-1.5">
                        <button
                          onClick={() => onSelectProposal(prop)}
                          className="p-1.5 rounded-md hover:bg-blue-50 text-slate-600 hover:text-blue-700 transition-colors"
                          title="Lihat Detail Lengkap"
                        >
                          <Eye className="w-4 h-4" />
                        </button>

                        {(userRole === 'reviewer' || userRole === 'admin_lppm') && (
                          <button
                            onClick={() => onOpenReviewModal(prop)}
                            className="p-1.5 rounded-md hover:bg-amber-50 text-slate-600 hover:text-amber-700 transition-colors"
                            title="Beri Nilai Reviewer"
                          >
                            <CheckCircle2 className="w-4 h-4" />
                          </button>
                        )}

                        <button
                          onClick={() => onOpenReportModal(prop)}
                          className="p-1.5 rounded-md hover:bg-emerald-50 text-slate-600 hover:text-emerald-700 transition-colors"
                          title="Lapor Monev & Rekam Luaran"
                        >
                          <FileText className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      ) : (
        /* GRID / CARD VIEW */
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredProposals.map((prop) => {
            const badge = getProposalStatusBadge(prop.status);
            return (
              <div
                key={prop.id}
                onClick={() => onSelectProposal(prop)}
                className="bg-white rounded-xl border border-slate-200 p-5 shadow-xs hover:border-blue-400 hover:shadow-md transition-all cursor-pointer flex flex-col justify-between"
              >
                <div>
                  <div className="flex items-center justify-between gap-2 mb-2">
                    <span className="font-mono text-[10px] text-slate-500">{prop.code}</span>
                    <span className={`text-[10px] font-semibold px-2 py-0.5 rounded-full border ${badge.bg} ${badge.color} ${badge.border}`}>
                      {badge.label}
                    </span>
                  </div>

                  <h3 className="font-bold text-sm text-slate-900 hover:text-blue-600 transition-colors line-clamp-2 leading-snug mb-2">
                    {prop.title}
                  </h3>

                  <div className="text-xs text-slate-600 space-y-1 mb-3">
                    <div className="font-medium text-slate-800">{prop.leader.name}</div>
                    <div className="text-slate-500 text-[11px]">{prop.leader.department} • {prop.leader.faculty}</div>
                    {prop.partner && (
                      <div className="text-emerald-700 text-[11px] font-medium flex items-center gap-1">
                        <Building className="w-3 h-3" /> Mitra: {prop.partner.name}
                      </div>
                    )}
                  </div>

                  <div className="bg-slate-50 rounded-lg p-2.5 text-[11px] space-y-1 border border-slate-100 mb-3">
                    <div className="text-slate-500 truncate">
                      <span className="font-medium text-slate-700">Skema:</span> {prop.scheme}
                    </div>
                    <div className="flex justify-between items-center text-slate-700 font-medium">
                      <span>Kesiapan TKT: {prop.tktCurrent} → {prop.tktTarget}</span>
                      <span className="text-blue-700 font-bold">
                        {formatRupiah(prop.approvedBudget || prop.requestedBudget)}
                      </span>
                    </div>
                  </div>
                </div>

                <div className="pt-3 border-t border-slate-100 flex items-center justify-between text-xs">
                  <span className="text-slate-400 text-[11px]">{prop.academicYear}</span>
                  <span className="text-blue-600 font-semibold flex items-center gap-1 hover:underline">
                    Buka Berkas <ChevronRight className="w-3.5 h-3.5" />
                  </span>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};
