import { Printer, X } from 'lucide-react';
import {
  getWalkthroughCategoryPct,
  getWalkthroughRating,
  getWalkthroughRatingLabel,
} from '@/business/walkthrough/selectors';
import {
  WALKTHROUGH_FORM_CATEGORIES,
  WALKTHROUGH_REPORT_FALLBACK_CAMPUS_LABEL,
  WALKTHROUGH_REPORT_FALLBACK_DIRECTOR_LABEL,
} from '@/shared/constants/walkthrough';
import type { WalkthroughGrowthPlan } from '@/business/walkthrough/types';
import type { WalkthroughSummaryWorkflow } from '@/components/walkthrough-summary/types';

interface WalkthroughPrintableReportProps {
  readonly summary: WalkthroughSummaryWorkflow;
}

function getReportPctClass(pct: number): string {
  if (pct >= 75) return 'bg-emerald-500';
  if (pct >= 50) return 'bg-amber-500';
  return 'bg-red-500';
}

function getReportTextClass(pct: number): string {
  if (pct >= 75) return 'text-emerald-600';
  if (pct >= 50) return 'text-amber-600';
  return 'text-red-600';
}

export function WalkthroughPrintableReport({ summary }: WalkthroughPrintableReportProps) {
  const teacherLabel = summary.selectedTeacher !== 'all' ? summary.selectedTeacher : 'All Staff';
  const directorLabel = summary.filteredCheckins[0]?.director_name || WALKTHROUGH_REPORT_FALLBACK_DIRECTOR_LABEL;
  const updateGrowthPlan = (field: keyof WalkthroughGrowthPlan, value: string) => {
    summary.setGrowthPlan((current) => ({ ...current, [field]: value }));
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold text-white">Printable Report</h3>
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => window.print()}
            className="flex items-center gap-1.5 px-4 py-2 bg-indigo-500/20 text-indigo-400 rounded-xl text-sm font-medium hover:bg-indigo-500/30 transition-colors border border-indigo-500/30"
          >
            <Printer size={14} /> Print Report
          </button>
          <button
            type="button"
            onClick={() => summary.setShowReport(false)}
            className="p-2 rounded-lg bg-slate-800 text-slate-400 hover:text-white transition-colors"
            aria-label="Close printable report"
          >
            <X size={16} />
          </button>
        </div>
      </div>

      <div className="bg-white rounded-2xl p-8 text-gray-800 print:shadow-none" id="printable-report">
        <div className="flex items-center justify-between border-b-2 border-indigo-500 pb-4 mb-6">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Walk-Through Performance Report</h1>
            <p className="text-sm text-gray-500 mt-1">
              {teacherLabel} - Review Period: Last {summary.timeRange} Days
            </p>
            <p className="text-sm text-gray-500">
              Director: {directorLabel} - {WALKTHROUGH_REPORT_FALLBACK_CAMPUS_LABEL}
            </p>
          </div>
          <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-violet-500 to-amber-400 flex items-center justify-center">
            <span className="text-white font-bold text-lg">F</span>
          </div>
        </div>

        <div className="mb-6">
          <h2 className="text-lg font-bold text-gray-900 mb-3">Overall Summary</h2>
          <div className="flex items-center gap-6 mb-3">
            <div className={`text-5xl font-black ${getReportTextClass(summary.overallPct)}`}>
              {summary.overallPct}%
            </div>
            <div>
              <span className={`inline-block px-3 py-1 rounded-full text-sm font-semibold ${
                summary.overallPct >= 75 ? 'bg-emerald-100 text-emerald-700' : summary.overallPct >= 50 ? 'bg-amber-100 text-amber-700' : 'bg-red-100 text-red-700'
              }`}>
                {summary.status.label}
              </span>
              <p className="text-sm text-gray-600 mt-1">{summary.filteredCheckins.length} walk-throughs in period</p>
            </div>
          </div>
          <p className="text-sm text-gray-600 bg-gray-50 rounded-lg p-3 italic">{summary.autoSummary}</p>
        </div>

        <div className="mb-6">
          <h2 className="text-lg font-bold text-gray-900 mb-3">Category Breakdown</h2>
          <div className="space-y-3">
            {WALKTHROUGH_FORM_CATEGORIES.map((category) => {
              const average = summary.categoryAverageByKey.get(category.key);
              if (!average) return null;

              const pct = getWalkthroughCategoryPct(average.avg, average.max);
              return (
                <div key={category.key} className="flex items-center gap-3">
                  <span className="text-sm text-gray-600 w-36">{category.shortLabel}</span>
                  <div className="flex-1 h-5 bg-gray-100 rounded-full overflow-hidden">
                    <div className={`h-full rounded-full ${getReportPctClass(pct)}`} style={{ width: `${pct}%` }} />
                  </div>
                  <span className="text-sm font-bold text-gray-700 w-12">{pct}%</span>
                </div>
              );
            })}
          </div>
        </div>

        <div className="mb-6">
          <h2 className="text-lg font-bold text-gray-900 mb-3">Detailed Ratings</h2>
          <table className="w-full text-sm border-collapse">
            <thead>
              <tr className="bg-gray-50">
                <th className="text-left p-2 border border-gray-200">Date</th>
                {WALKTHROUGH_FORM_CATEGORIES.map((category) => (
                  <th key={category.key} className="text-center p-2 border border-gray-200 text-xs">{category.shortLabel}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {summary.filteredCheckins.slice(0, 10).map((checkin, index) => (
                <tr key={checkin.id} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                  <td className="p-2 border border-gray-200 text-xs">{checkin.check_in_date}</td>
                  {WALKTHROUGH_FORM_CATEGORIES.map((category) => {
                    const value = getWalkthroughRating(checkin, category.key);
                    const pct = (value / category.max) * 100;
                    return (
                      <td key={category.key} className={`p-2 border border-gray-200 text-center text-xs font-medium ${getReportTextClass(pct)}`}>
                        {getWalkthroughRatingLabel(value, category.key)}
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="border-t-2 border-indigo-500 pt-4">
          <h2 className="text-lg font-bold text-gray-900 mb-3">Growth Plan</h2>
          <div className="grid grid-cols-2 gap-4">
            <label className="block">
              <span className="text-sm font-semibold text-gray-700 block mb-1">Strengths Identified</span>
              <textarea value={summary.growthPlan.strengths} onChange={(event) => updateGrowthPlan('strengths', event.target.value)} rows={3} className="w-full border border-gray-300 rounded-lg p-2 text-sm" placeholder="Enter strengths..." />
            </label>
            <label className="block">
              <span className="text-sm font-semibold text-gray-700 block mb-1">Focus Areas</span>
              <textarea value={summary.growthPlan.focusAreas} onChange={(event) => updateGrowthPlan('focusAreas', event.target.value)} rows={3} className="w-full border border-gray-300 rounded-lg p-2 text-sm" placeholder="Enter focus areas..." />
            </label>
            <label className="block">
              <span className="text-sm font-semibold text-gray-700 block mb-1">Agreed Next Steps</span>
              <textarea value={summary.growthPlan.nextSteps} onChange={(event) => updateGrowthPlan('nextSteps', event.target.value)} rows={3} className="w-full border border-gray-300 rounded-lg p-2 text-sm" placeholder="Enter next steps..." />
            </label>
            <label className="block">
              <span className="text-sm font-semibold text-gray-700 block mb-1">Review Date</span>
              <input type="date" value={summary.growthPlan.reviewDate} onChange={(event) => updateGrowthPlan('reviewDate', event.target.value)} className="w-full border border-gray-300 rounded-lg p-2 text-sm" />
            </label>
          </div>
        </div>
      </div>
    </div>
  );
}
